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

后端 未结 9 1362
星月不相逢
星月不相逢 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 06:57

    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
    }
    

提交回复
热议问题