typeof() 有效,GetType() 在检索属性时无效 [英] typeof() works, GetType() doesn't works when retrieving property

查看:39
本文介绍了typeof() 有效,GetType() 在检索属性时无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过反射检索 private 属性的值

I am trying to retrieve a value of private property via reflection

// definition
public class Base
{
    private bool Test { get { return true; } }
}
public class A: Base {}
public class B: Base {}

// now
object obj = new A(); // or new B()

// works
var test1 = typeof(Base).GetProperty("Test", BindingFlags.Instance | BindingFlags.NonPublic);
if(test1 != null) // it's not null
    if((bool)test1.GetValue(obj, null)) // it's true
        ...

// doesn't works!
var test2 = obj.GetType().GetProperty("Test", BindingFlags.Instance | BindingFlags.NonPublic);
if(test2 != null) // is null !
    ...

我的错误在哪里?我将需要使用 object 来传递实例,因为一些 private 属性将在 AB 中声明>.有时甚至隐藏(使用 new)Base 属性.

Where is my mistake? I will need to use object to pass instance, because some of private properties will be declared in the A or B. And even hiding (with new) Base properties sometimes.

推荐答案

Test 是 Base 私有的.它对继承的 A/B 类不可见.如果你想让它对继承类可见,你应该让它protected.

Test is private to Base. It is not visible to the inherited A/B classes. You should make it protected if you want it visible to the inheriting class.

或者如果继承树只有一层,你可以使用GetType().BaseType.

Or you can use GetType().BaseType if the inheritance tree is just one level.

public class Base
{
    private bool Test { get { return true; } }
    protected bool Test2 { get { return true; } }
}
public class A : Base { }
public class B : Base { }

[TestMethod]
public void _Test()
{
    object obj = new A(); // or new B()         

    Assert.IsNotNull(typeof(Base).GetProperty("Test", BindingFlags.Instance | BindingFlags.NonPublic));
    Assert.IsNotNull(typeof(Base).GetProperty("Test2", BindingFlags.Instance | BindingFlags.NonPublic));

    Assert.IsNull(typeof(A).GetProperty("Test", BindingFlags.Instance | BindingFlags.NonPublic));
    Assert.IsNotNull(typeof(A).GetProperty("Test2", BindingFlags.Instance | BindingFlags.NonPublic));

    Assert.IsNull(typeof(A).GetProperty("Test", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy));
    Assert.IsNotNull(typeof(A).GetProperty("Test2", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy));

    Assert.IsNull(obj.GetType().GetProperty("Test", BindingFlags.Instance | BindingFlags.NonPublic));
    Assert.IsNotNull(obj.GetType().GetProperty("Test2", BindingFlags.Instance | BindingFlags.NonPublic));

    Assert.IsNotNull(obj.GetType().BaseType.GetProperty("Test", BindingFlags.Instance | BindingFlags.NonPublic));
    Assert.IsNotNull(obj.GetType().BaseType.GetProperty("Test2", BindingFlags.Instance | BindingFlags.NonPublic));

}

这篇关于typeof() 有效,GetType() 在检索属性时无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆