[英]Reflection (?) - Check for null or empty for each property/field in a class?
我有一个简单的类:
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)或empty / null(对于字符串),那么我将转换并将该属性的值添加到List<string>
?
谢谢。
你可以使用LINQ来做到这一点:
List<string> 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<string> 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<string> 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这样的接口中,并在需要这种功能的每个类中实现,显然如果有很多类,你可能必须坚持使用反射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.