PropertyInfo、FieldInfo、MemberInfo的区别 [整理]C#反射(Reflection)详解

public class TestClass
{
    private int a = 1;//私有一律获取不到
    public int b
    {
        get { return 2; }
        set { value = 2; }
    }
    public int c = 3;
}

public static void TestMethod()
{
    TestClass test = new TestClass();
    PropertyInfo[] pro = test.GetType().GetProperties();
    FieldInfo[] fil = test.GetType().GetFields();
    MemberInfo[] men = test.GetType().GetMembers();

    foreach (var item in pro)//仅能获取到b属性(输出b=2)
    {
        Console.WriteLine("PropertyInfo: " + item.Name  +"=" + item.GetValue(test, null));
    }
    foreach (FieldInfo item in fil)//仅能获取到c字段(输出c=2)
    {
        Console.WriteLine("FieldInfo: " + item.Name + "=" + item.GetValue(test));
    }
    foreach (MemberInfo item in fil)//仅能获取到c字段(输出c)
    {
        Console.WriteLine("MemberInfo: "+ item.Name );
    }
}

参考

[整理]C#反射(Reflection)详解

猜你喜欢

转载自www.cnblogs.com/code1992/p/11348064.html