使用接口的继承属性的属性

时间:2016-12-27 20:56:11

标签: c# inheritance custom-attributes

我一直在尝试使用已在接口中声明的属性的属性。

假设:

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

现在,根据我的读法,带继承= true的GetCustomAttribute()应返回继承的属性,但看起来它不起作用。

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

为什么不起作用?以及如何获取属性?

2 个答案:

答案 0 :(得分:1)

Child没有任何自定义属性,ITest包含这些属性,因此您必须在GetCustomAttributes的成员上致电ITest

继承和实现之间存在差异。如果Child派生自某个具有y属性的My1Attribute属性的基类,则继承会很好。

在您的情况下,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; }
}

答案 1 :(得分:0)

这只是草图,而不是详细的答案。它应该从Child开始,了解如何找到属性。

您可以使用typeof(Child).GetInterfaces()获取一个数组,您可以从中看到Child实现ITest。假设t是你从数组中得到的typeof(ITest),那么:

typeof(Child).GetInterfaceMap(t)

会为您提供一个结构("地图"),以便从getget_y中查看属性获取者(Child访问者).TargetMethods的内容)对应于界面(.InterfaceMethods)。答案是另一个get_y当然。您拥有的是MethodInfoget属性y访问者的ITest。要查找房产本身,请参阅例如this answer to Finding the hosting PropertyInfo from the MethodInfo of getter/setter。获得属性信息后,请检查其自定义属性,以查找My1Attribute及其值x