2016-12-27 10 views
1

インターフェイスで宣言されているプロパティの属性を使用しようとしました。インターフェイスからの継承プロパティの属性の使用

仮定します

[AttributeUsage(AttributeTargets.Property, Inherited=true)] 
class My1Attribute : Attribute 
{ 
    public int x { get; set; } 
} 

interface ITest 
{ 
    [My1] 
    int y { get; set; } 
} 

class Child : ITest 
{ 
    public Child() { } 

    public int y { get; set; } 
} 

を、私が読んだものから、GetCustomAttributeを()継承=真では、継承された属性を返す必要がありますが、それはそれは動作しません見えます。

Attribute my = typeof(Child).GetProperty("y").GetCustomAttribute(typeof(My1Attribute), true); // my == null 

なぜ機能しないのですか?どのように属性を取得できますか?

答えて

1

Childにはカスタム属性がありません。ITestにはそれらがありますので、ITestのメンバーにGetCustomAttributesと電話する必要があります。

継承と実装の間に違いがあります。 Childが、My1Attributeで修飾されたyプロパティを持つ基本クラスから派生した場合、継承は問題ありません。あなたのケースでは

Child ITestを実装し、 ITestは、継承階層の外に、異なるタイプです。

void Main() 
{ 
    var my1Attribute = typeof(ITest).GetProperty("y").GetCustomAttribute(typeof(My1Attribute)) as My1Attribute; 
    Console.WriteLine(my1Attribute.x); // Outputs: 0 
} 

[AttributeUsage(AttributeTargets.Property, Inherited = true)] 
class My1Attribute : Attribute 
{ 
    public int x { get; set; } 
} 

interface ITest 
{ 
    [My1] 
    int y { get; set; } 
} 

class Child : ITest 
{ 
    public Child() { } 

    public int y { get; set; } 
} 
0

これは単なるスケッチであり、詳細な解答ではありません。 Childから始まる属性の検索方法を知っておく必要があります。

typeof(Child).GetInterfaces()を使用すると、ChildITestを実装していることがわかる配列を取得できます。

typeof(Child).GetInterfaceMap(t) 

は(「マップ」)(.TargetMethods中)Childからどのようなプロパティのゲッター(getアクセサ)get_y見るためにあなたの構造を与えるに対応:ttypeof(ITest)あなたがして、配列の外に出たされたと仮定しますインタフェース(.InterfaceMethods)にあります。答えはもちろん、別のget_yです。だからあなたはITestyプロパティのgetアクセサーのMethodInfoです。プロパティ自体を見つける方法については、 this answer to Finding the hosting PropertyInfo from the MethodInfo of getter/setter。プロパティ情報を取得したら、カスタム属性を調べてMy1Attributeとその値がxであることを確認します。

関連する問題