简体   繁体   English

如何检查对象的所有属性是否为空或为空?

[英]How to check all properties of an object whether null or empty?

I have an object lets call it ObjectA我有一个对象让我们称之为ObjectA

and that object has 10 properties and those are all strings.该对象有 10 个属性,这些都是字符串。

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

is there anyway to check to see whether all these properties are null or empty?无论如何要检查所有这些属性是否为空或为空?

So any built-in method that would return true or false?那么任何会返回真或假的内置方法?

If any single of them is not null or empty then the return would be false.如果其中任何一个不为 null 或为空,则返回将为 false。 If all of them are empty it should return true.如果它们都是空的,它应该返回true。

The idea is I do not want to write 10 if statement to control if those properties are empty or null.这个想法是我不想写 10 个 if 语句来控制这些属性是空的还是空的。

Thanks谢谢

You can do it using 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 suggested an alternative using LINQ : Matthew Watson 建议使用LINQ的替代方案:

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

I suppose you want to make sure that all properties are filled in.我想您想确保填写所有属性。

A better option is probably by putting this validation in the constructor of your class and throw exceptions if validation fails.更好的选择可能是将此验证放在类的构造函数中,如果验证失败则抛出异常。 That way you cannot create a class that is invalid;这样你就不能创建一个无效的类; catch exceptions and handle them accordingly.捕获异常并相应地处理它们。

Fluent validation is a nice framework ( http://fluentvalidation.codeplex.com ) for doing the validation. Fluent 验证是一个很好的框架 ( http://fluentvalidation.codeplex.com ) 用于进行验证。 Example:例子:

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

Usage:用法:

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

PS - Using reflection for this kind of thing just makes your code harder to read. PS - 对这种事情使用反射只会使您的代码更难阅读。 Using validation as shown above makes it explicitly clear what your rules are;使用如上所示的验证可以明确地明确您的规则是什么; and you can easily extend them with other rules.您可以使用其他规则轻松扩展它们。

The following code returns if any property is not null.如果任何属性不为空,则以下代码返回。

  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.

Here you go干得好

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

and here's the class这是课程

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

A slightly different way of expressing the linq to see if all string properties of an object are non null and non empty:一种稍微不同的表达 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));
}

Note if you've got a data structural hierarchy and you want to test everything in that hierarchy, then you can use a recursive method.请注意,如果您有一个数据结构层次结构并且想要测试该层次结构中的所有内容,那么您可以使用递归方法。 Here's a quick example:这是一个简单的例子:

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

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

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

you can use reflection and extension methods to do this.您可以使用反射和扩展方法来做到这一点。

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

then use it on any object with string properties然后在任何具有字符串属性的对象上使用它

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

No, I don't think there is a method to do exactly that.不,我不认为有一种方法可以做到这一点。

You'd be best writing a simple method that takes your object and returns true or false.您最好编写一个简单的方法来获取您的对象并返回 true 或 false。

Alternatively, if the properties are all the same, and you just want to parse through them and find a single null or empty, perhaps some sort of collection of strings would work for you?或者,如果属性都相同,并且您只想解析它们并找到单个 null 或空,那么某种字符串集合可能对您有用?

You can try the following query :您可以尝试以下查询:

if the object is "referenceKey" (where few properties may be null )如果对象是“referenceKey”(很少有属性可能是 null )

referenceKey.GetType().GetProperties().Where(x => x.GetValue(referenceKey) == null)

I need to count the properties where the value is set to not Null, so I have used the following query :我需要计算值设置为非 Null 的属性,因此我使用了以下查询:

 var countProvidedReferenceKeys = referenceKey.GetType().GetProperties().Where(x => x.GetValue(referenceKey) != null).Count();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM