反射 - 在类中检查每个属性/字段是否为空或空字符串?

26

我有一个简单的类如下:

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; }
}

如何检查类中的每个属性是否为非空 (int) 或非空/空值 (对于字符串),然后将该属性的值转换并添加到 List<string> 中?

谢谢。

6个回答

36

你可以使用 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();

如果属性的类型是 int,且值为 0,那么 prop.GetValue 会返回 null 吗? - dtb
@dtb,不是的,在那种情况下它会返回0 - Frédéric Hamidi
@Frederic:你是想要包含这些0还是将它们过滤掉? - James Michael Hare
@James,我想要包含它们,因为提问者显然需要。 - Frédéric Hamidi
抱歉打扰,这有点老了,但如果我想检查一个short、int或long是否等于0怎么办?查询会是什么样子...我拼凑了一些代码,但实际上看起来非常丑陋。 - Dimitar Dimitrov

9

虽然不是最好的方法,但大致上可以这样做:

假设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
}

2
我认为对于值对象的空值检查,需要使用And(&&)条件而不是Or(||)条件进行检查。 - Sambath Kumar S

2

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

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();

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

0

你真的需要反射吗?像 bool IsNull 这样的属性实现对你来说是一个案例吗?你可以将其封装在接口 INullableEntity 中,并在需要此功能的每个类中实现,显然如果有很多类,也许你必须坚持使用反射。


0
这是一个例子:
foreach (PropertyInfo item in typeof(FilterParams).GetProperties()) {
    if (item != null && !String.IsNullOrEmpty(item.ToString()) {
        //add to list, etc
     } 
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接