反射(?) - 检查类中每个属性/字段的null或为空?

Sax*_*man 20 .net c# reflection

我有一个简单的类:

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; }
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Fré*_*idi 32

你可以使用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();
Run Code Online (Sandbox Code Playgroud)


Mrc*_*ief 6

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

假设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
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为对于值对象空检查。需要检查 And (&amp;&amp;) 条件而不是 OR (||) (2认同)