如何检查对象的所有属性是null还是空?

akd*_*akd 60 c# properties

我有一个对象让我们调用它 ObjectA

并且该对象有10个属性,这些属性都是字符串.

 var myObject = new {Property1="",Property2="",Property3="",Property4="",...}
Run Code Online (Sandbox Code Playgroud)

无论如何要检查所有这些属性是空还是空?

那么任何返回true或false的内置方法呢?

如果它们中的任何一个不为null或为空,则返回将为false.如果所有这些都是空的,它应该返回true.

我的想法是,我不想编写10 if语句来控制这些属性是空还是null.

谢谢

hel*_*elb 81

你可以使用Reflection做到这一点

bool IsAnyNullOrEmpty(object myObject)
{
    foreach(PropertyInfo pi in myObject.GetType().GetProperties())
    {
        if(pi.PropertyType == typeof(string))
        {
            string value = (string)pi.GetValue(myObject);
            if(string.IsNullOrEmpty(value))
            {
                return true;
            }
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

Matthew Watson提出了使用LINQ的替代方案:

return myObject.GetType().GetProperties()
    .Where(pi => pi.PropertyType == typeof(string))
    .Select(pi => (string)pi.GetValue(myObject))
    .Any(value => string.IsNullOrEmpty(value));
Run Code Online (Sandbox Code Playgroud)

  • 如果您有 ID 属性或需要排除的内容,您可以检查: if (pi.Name.Equals("InfoID") || pi.Name.Equals("EmployeeID") || pi.Name.Equals("LastUpdated “)) 继续; (3认同)

L-F*_*our 15

我想你要确保填写所有属性.

更好的选择可能是将此验证放在类的构造函数中,并在验证失败时抛出异常.这样你就无法创建一个无效的类; 捕获异常并相应地处理它们.

流畅的验证是一个很好的框架(http://fluentvalidation.codeplex.com),用于进行验证.例:

public class CustomerValidator: AbstractValidator<Customer> 
{
    public CustomerValidator()
    {
        RuleFor(customer => customer.Property1).NotNull();
        RuleFor(customer => customer.Property2).NotNull();
        RuleFor(customer => customer.Property3).NotNull();
    }
}

public class Customer
{
    public Customer(string property1, string property2, string property3)
    {
         Property1  = property1;
         Property2  = property2;
         Property3  = property3;
         new CustomerValidator().ValidateAndThrow();
    }

    public string Property1 {get; set;}
    public string Property2 {get; set;}
    public string Property3 {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

用法:

 try
 {
     var customer = new Customer("string1", "string", null);
     // logic here
 } catch (ValidationException ex)
 {
     // A validation error occured
 }
Run Code Online (Sandbox Code Playgroud)

PS - 对这种事物使用反射只会让你的代码更难阅读.使用上面显示的验证可以明确说明您的规则是什么; 并且您可以使用其他规则轻松扩展它们.


Ond*_*cek 9

干得好

var instOfA = new ObjectA();
bool isAnyPropEmpty = instOfA.GetType().GetProperties()
     .Where(p => p.GetValue(instOfA) is string) // selecting only string props
     .Any(p => string.IsNullOrWhiteSpace((p.GetValue(instOfA) as string)));
Run Code Online (Sandbox Code Playgroud)

这是班级

class ObjectA
{
    public string A { get; set; }
    public string B { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

  • 编辑你的问题,并在那里添加你正在尝试的确切代码,并清楚地解释你得到的错误,请.我发布了一般性答案,因为你问了一个普遍的问题.您的问题中没有关于视图和控制器的信息. (2认同)

Val*_*deh 8

如果任何属性不为空,则以下代码返回。

  return myObject.GetType()
                 .GetProperties() //get all properties on object
                 .Select(pi => pi.GetValue(myObject)) //get value for the property
                 .Any(value => value != null); // Check if one of the values is not null, if so it returns true.
Run Code Online (Sandbox Code Playgroud)


Mat*_*son 5

表达linq以查看对象的所有字符串属性是否为非null且非空的略有不同的方式:

public static bool AllStringPropertyValuesAreNonEmpty(object myObject)
{
    var allStringPropertyValues = 
        from   property in myObject.GetType().GetProperties()
        where  property.PropertyType == typeof(string) && property.CanRead
        select (string) property.GetValue(myObject);

    return allStringPropertyValues.All(value => !string.IsNullOrEmpty(value));
}
Run Code Online (Sandbox Code Playgroud)