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

时间:2014-03-27 09:19:20

标签: c# properties

我有一个对象,可以调用它ObjectA

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

 var myObject = new {Property1="",Property2="",Property3="",Property4="",...}

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

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

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

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

谢谢

9 个答案:

答案 0 :(得分:75)

您可以使用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;
}

Matthew Watson使用LINQ提出了另一种选择:

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

答案 1 :(得分:14)

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

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

Fluent验证是一个很好的框架(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;}
}

用法:

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

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

答案 2 :(得分: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)));

这是班级

class ObjectA
{
    public string A { get; set; }
    public string B { get; set; }
}

答案 3 :(得分: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));
}

答案 4 :(得分:2)

您可以使用反射和扩展方法来执行此操作。

using System.Reflection;
public static class ExtensionMethods
{
    public static bool StringPropertiesEmpty(this object value)
    {
        foreach (PropertyInfo objProp in value.GetType().GetProperties())
        {
            if (objProp.CanRead)
            {
                object val = objProp.GetValue(value, null);
                if (val.GetType() == typeof(string))
                {
                    if (val == "" || val == null)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

然后在任何具有字符串属性的对象上使用它

test obj = new test();
if (obj.StringPropertiesEmpty() == true)
{
    // some of these string properties are empty or null
}

答案 5 :(得分:2)

请注意,如果您拥有数据结构层次结构,并且希望测试该层次结构中的所有内容,则可以使用递归方法。这是一个简单的例子:

static bool AnyNullOrEmpty(object obj) {
  return obj == null
      || obj.ToString() == ""
      || obj.GetType().GetProperties().Any(prop => AnyNullOrEmpty(prop.GetValue(obj)));
}

答案 6 :(得分:2)

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

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

答案 7 :(得分:0)

不,我认为没有办法可以做到这一点。

你最好写一个简单的方法来获取你的对象并返回true或false。

或者,如果属性都是相同的,并且您只想解析它们并找到一个null或空,那么某些字符串集合可能对您有用吗?

答案 8 :(得分:0)

仅检查所有属性是否为空:

bool allPropertiesNull = !myObject.GetType().GetProperties().Any(prop => prop == null);