【问题标题】:Using attribute of inherited property from an interface使用从接口继承的属性的属性
【发布时间】:2017-05-12 03:37:05
【问题描述】:

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

假设:

[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

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

【问题讨论】:

    标签: c# inheritance custom-attributes


    【解决方案1】:

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

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

    typeof(Child).GetInterfaceMap(t)
    

    会给你一个结构(“map”)来查看来自Child.TargetMethods)的属性getter(get访问器)get_y在接口(@98​​7654333@)中对应的内容。答案当然是另一个get_y。所以你拥有的是ITesty 属性的get 访问器的MethodInfo。要查找属性本身,请参见例如this answer to Finding the hosting PropertyInfo from the MethodInfo of getter/setter。获得属性信息后,检查其自定义属性以找到 My1Attribute 及其值 x

    【讨论】:

      【解决方案2】:

      Child 没有任何自定义属性,ITest 有它们,所以你必须在ITest 的成员上调用GetCustomAttributes

      继承和实现是有区别的。如果Child 派生自某个基类,该基类的y 属性用My1Attribute 装饰,那么继承就可以了。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-06
        • 2011-01-09
        • 2019-10-24
        • 2011-10-06
        • 2021-12-14
        • 1970-01-01
        • 2019-01-09
        • 2012-05-08
        相关资源
        最近更新 更多