2016-12-27 81 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實現ITestITest是不同類型的,繼承層次之外。

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()來獲得一個數組,從中您可以看到Child實現了ITest。假設ttypeof(ITest)你下了陣,則:

typeof(Child).GetInterfaceMap(t) 

會給你一個結構(「地圖」),看看有什麼屬性getter(get訪問)get_yChild(在.TargetMethods)對應於在界面(.InterfaceMethods)中。當然,答案是get_y。因此,您所擁有的是ITesty財產的get訪問者的MethodInfo。要查找酒店本身,請參閱this answer to Finding the hosting PropertyInfo from the MethodInfo of getter/setter。一旦你有屬性信息,檢查它的自定義屬性找到My1Attribute和它的值x