2016-09-14 8 views
0

を返さない私は、次の記事提案GetPropertiesのが期待される特性

  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

に従っていたし、私のテストを修正しました下記のようにバインディングフラグをインクルードします。

目標: 私の最終目標は、取得した財産がreadOnlyであるかどうかをテストすることです。

問題: ChildClass/Inheritedクラスのプロパティは、リフレクションで表示されません。

プロパティがチェックするかどうかのテスト。exists - fails。私は私が実際に私を知っているか理解しなかったという事実を逃した謝罪親クラスのプロパティ

//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; } 

} 

EDIT 2016年9月14日 あるResultで唯一のプロパティGetProperties(BindingFlags.FlattenHiearchy)リターンに

私がと言ったらAssert.NotNullと言ってもいいですが、それは私が最終目標を達成するのを助けません - それがreadonlyであるかどうかを確認するのを助けません - これが可能であれば誰かが確認できますか?ありがとう!

答えて

1

public readonly Guid Idは、フィールドであり、プロパティではありません。代わりにGetFieldメソッドを使用します。

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

あなたはそれがFieldInfoクラスのIsInitOnlyプロパティを見てreadonlyであるかどうかを確認することができます。

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

確かに、これは動作しますが、どのように私はそこにそれを私の目的を達成するだろうが記載されている - 私はそれが読み取り専用であるかどうかを確認したいと思う意味 - それはフィールドであることを考えることはできないということでしょうか? – Jaya

+0

申し訳ありませんが、私はより明確にすべきでした。 – Jaya

+0

@JS_GodBlessAll私の答えの2番目の部分では、結果から 'IsInitOnly'プロパティを調べることで確認できると述べました。それはあなたのために働いたのですか? –

関連する問題