2016-09-14 59 views
0

我的確遵循了以下職位的建議的GetProperties與適當的BindingFlags繼承/子類不返回預期的性能

  1. Reflecting over all properties of an interface, including inherited ones?
  2. How do you get the all properties of a class and its base classes (up the hierarchy) with Reflection? (C#)
  3. Using GetProperties() with BindingFlags.DeclaredOnly in .NET Reflection

和修改我的測試包括如下所示的bindingflags。

目標: 我的最終目標是測試如果獲取的屬性是readOnly

問題: ChildClass /繼承的類屬性甚至不反映出來。

測試以檢查屬性exists - fails

GetProperties(BindingFlags.FlattenHiearchy)回報只有一個屬性,它是Result這是父類的屬性

//My failing test 
Assert.NotNull(typeof(ChildClass).GetProperty("Id",BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)); 

//My Alternate version which still fails 
Assert.NotNull(typeof(ChildClass).GetProperty("Id",BindingFlags.FlattenHierarchy)); 

// My class structure against which my test is running. 
class ChildClass:BaseClass<MyCustomObject> 
{ 
    public ChildClass (Guid id) 
    { 
     Id = id; 
    } 

    public readonly Guid Id; 
} 

class BaseClass<T>:IMyInterFace<T> 
{ 
    public T Result { get; private set; } 
} 

public interface IMyInterFace<T> 
{ 
    T Result { get; } 

} 

編輯 2016年9月14日 我很抱歉,我錯過了事實,實際上我知道或瞭解我可以Assert.NotNull如果我說GetField - 但那不會幫助我實現最終目標 - 檢查它是否爲readonly - 我現在不確定這是否甚至可以有人確認?謝謝!。

回答

1

public readonly Guid Id,而不是一個屬性。使用GetField方法代替:

typeof(ChildClass).GetField("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); 

您可以檢查,看它是否是readonly通過查看FieldInfo類的IsInitOnly財產。

var result = typeof(ChildClass).GetField("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); 
Assert.IsTrue(result.IsInitOnly); 
+0

當然,這是可行的,但我將如何實現我的目標 - 這意味着我想檢查它是否只讀 - 是不可能的,因爲它是一個字段? – Jaya

+0

對不起,我應該更清楚了。 – Jaya

+0

@JS_GodBlessAll在我的回答的第二部分中,我表示可以通過查看結果中的IsInitOnly屬性來檢查。這對你有用嗎? –