reflection(?) – 检查类中每个属性/字段的null或为空?

我有一个简单的类:

public class FilterParams { public string MeetingId { get; set; } public int? ClientId { get; set; } public string CustNum { get; set; } public int AttendedAsFavor { get; set; } public int Rating { get; set; } public string Comments { get; set; } public int Delete { get; set; } } 

如何检查类中的每个属性,如果它们不是null(int)或null / null(对于字符串),那么我将转换并将该属性的值添加到List

谢谢。

你可以使用LINQ来做到这一点:

 List values = typeof(FilterParams).GetProperties() .Select(prop => prop.GetValue(yourObject, null)) .Where(val => val != null) .Select(val => val.ToString()) .Where(str => str.Length > 0) .ToList(); 

不是最好的方法,但大致:

假设obj是你的类的实例:

 Type type = typeof(FilterParams); foreach(PropertyInfo pi in type.GetProperties()) { object value = pi.GetValue(obj, null); if(value != null && !string.IsNullOrEmpty(value.ToString())) // do something } 

如果你没有很多这样的类而没有太多的属性,最简单的解决方案可能是编写一个迭代器块来检查和转换每个属性:

 public class FilterParams { // ... public IEnumerable GetValues() { if (MeetingId != null) yield return MeetingId; if (ClientId.HasValue) yield return ClientId.Value.ToString(); // ... if (Rating != 0) yield return Rating.ToString(); // ... } } 

用法:

 FilterParams filterParams = ... List values = filterParams.GetValues().ToList(); 
 PropertyInfo[] properties = typeof(FilterParams).GetProperties(); foreach(PropertyInfo property in properties) { object value = property.GetValue(SomeFilterParamsInstance, null); // preform checks on value and etc. here.. } 

这是一个例子:

 foreach (PropertyInfo item in typeof(FilterParams).GetProperties()) { if (item != null && !String.IsNullOrEmpty(item.ToString()) { //add to list, etc } } 

你真的需要反思吗? 实现像bool IsNull这样的属性就是你的理由吗? 你可以将它封装在像INullableEntity这样的接口中,并在每个需要这种function的类中实现,显然如果有很多类,你可能必须坚持使用reflection。