Programing

객체의 모든 속성이 null인지 비어 있는지 확인하는 방법은 무엇입니까?

lottogame 2020. 12. 8. 07:38
반응형

객체의 모든 속성이 null인지 비어 있는지 확인하는 방법은 무엇입니까?


나는 그것을 호출 할 개체가 있습니다 ObjectA

그 객체는 10 개의 속성을 가지고 있고 그것들은 모두 문자열입니다.

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

어쨌든 이러한 모든 속성이 null인지 비어 있는지 확인할 수 있습니까?

그렇다면 true 또는 false를 반환하는 내장 메서드가 있습니까?

그중 하나가 null이 아니거나 비어 있지 않으면 반환은 false입니다. 모두 비어 있으면 true를 반환해야합니다.

아이디어는 해당 속성이 비어 있거나 null인지 제어하기 위해 10 if 문을 작성하고 싶지 않다는 것입니다.

감사


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

모든 속성이 채워져 있는지 확인하고 싶다고 가정합니다.

더 나은 옵션은이 유효성 검사를 클래스 생성자에 넣고 유효성 검사가 실패하면 예외를 throw하는 것입니다. 이렇게하면 잘못된 클래스를 만들 수 없습니다. 예외를 포착하고 그에 따라 처리합니다.

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
 }

추신-이런 종류의 일에 리플렉션을 사용하면 코드를 읽기가 더 어려워집니다. 위에 표시된대로 유효성 검사를 사용하면 규칙이 무엇인지 명확하게 알 수 있습니다. 다른 규칙으로 쉽게 확장 할 수 있습니다.


여기 있습니다

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

객체의 모든 문자열 속성이 null이 아니고 비어 있지 않은지 확인하기 위해 linq를 표현하는 약간 다른 방법입니다.

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

다음 코드는 속성이 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.

이를 위해 리플렉션 및 확장 메서드를 사용할 수 있습니다.

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
}

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

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.

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?


To only check if all properties are null:

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

참고URL : https://stackoverflow.com/questions/22683040/how-to-check-all-properties-of-an-object-whether-null-or-empty

반응형