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

后端 未结 9 1312
星月不相逢
星月不相逢 2020-11-28 06:41

I have an object lets call it ObjectA

and that object has 10 properties and those are all strings.

 var myObject = new {Property1=\"\",P         


        
9条回答
  •  攒了一身酷
    2020-11-28 07:14

    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. Example:

    public class CustomerValidator: AbstractValidator 
    {
        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. Using validation as shown above makes it explicitly clear what your rules are; and you can easily extend them with other rules.

提交回复
热议问题