簡體   English   中英

typeof()有效,GetType()在檢索屬性時不起作用

[英]typeof() works, GetType() doesn't works when retrieving property

我試圖通過反射檢索private財產的價值

// 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聲明。 甚至有時隱藏(使用newBase屬性。

測試對Base是私有的。 它對繼承的A / B類不可見。 如果您希望繼承類可以看到它,則應該使其protected

或者,如果繼承樹只是一個級別,則可以使用GetType().BaseType

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));

}

A繼承自Base ,因此您需要告訴GetProperty在基類中查找屬性。 傳遞FlattenHierarchy標志:

GetProperty("Test", BindingFlags.Instance 
      | BindingFlags.NonPublic 
      | BindingFlags.FlattenHeirarchy) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM