.NET 如何判断一个对象中是否包含NULL值?

2025-01-10 01:25:12
推荐回答(2个)
回答1:


public static string AnyPropertyIsNull(T t) where T : class

{

PropertyInfo[] rs =  t.GetType().GetProperties();

foreach( PropertyInfo prop in rs )

{

PropertyInfo Info = typeof(T).GetProperty(prop.Name);

object value =Info.GetValue(t);

if( value == null )

{

return string.Format("Property: {0}, null value!", prop.Name);

}

}

return null;

}

回答2:

这样你看行不行?

    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.b = new B();
            foreach (var pi in typeof(A).GetProperties())
            {
                object v = pi.GetValue(a, new object[] { });
                //输出值为null的属性名称
                if (v == null)
                    Console.WriteLine(pi.Name);
            }
            Console.ReadLine();
        }
    }

    public class A
    {
        public B b { get; set; }
    }

    public class B
    {

    }