首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自定义属性类继承“继承”AttributeUsage标志吗?

自定义属性类继承“继承”AttributeUsage标志吗?
EN

Stack Overflow用户
提问于 2013-02-19 10:39:57
回答 1查看 3.1K关注 0票数 9

考虑以下情况:

  • 基类BaseAttribute有一个指定不可继承的AttributeUsageAttribute (Inherited = False)。
  • 派生属性类DerivedAttribute继承自该基属性类。
  • 基域类Base应用了派生属性。
  • 从基域类继承的域类Derived被要求提供它的自定义属性,包括继承属性(inherit: true)。

以下是相应的代码:

代码语言:javascript
复制
using System;
using System.Linq;

namespace ConsoleApplication26
{
  class Program
  {
    static void Main ()
    {
      var attributes = typeof (Derived).GetCustomAttributes (true);
      foreach (var attribute in attributes)
      {
        Console.WriteLine (
            "{0}: Inherited = {1}",
            attribute.GetType().Name,
            attribute.GetType().GetCustomAttributes (typeof (AttributeUsageAttribute), true).Cast<AttributeUsageAttribute>().Single().Inherited);
      }
    }
  }

  [AttributeUsage (AttributeTargets.All, Inherited = false)]
  public class BaseAttribute : Attribute
  {
  }

  public class DerivedAttribute : BaseAttribute
  {
  }

  [Derived]
  public class Base
  {
  }

  public class Derived : Base
  {
  }
}

在这个场景中,GetCustomAttributes API返回DerivedAttribute类的一个实例。我本以为它不会返回那个实例,因为http://msdn.microsoft.com/en-us/library/system.attributeusageattribute.aspxAttributeUsageAttribute本身是可继承的。

现在,这是一个bug,还是被期望/记录在某个地方?

注(2013-02-20):实验表明,BaseAttribute类的AttributeTargets部分确实是由DerivedAttribute类继承的。例如,当我将BaseAttribute上允许的目标更改为AttributeTargets.Method时,C#编译器将不允许我将DerivedAttribute应用于类。因此,Inherited = false部分不被DerivedAttribute继承是没有意义的,因此我倾向于考虑GetCustomAttributes实现中的一个bug。

EN

回答 1

Stack Overflow用户

发布于 2015-01-12 09:01:28

根据.NET 4.0中的元数据,AttributeUsageAttribute类被标记为[AttributeUsage(AttributeTargets.Class, Inherited = true)]。因此,如果您的属性类(在您的示例中是BaseAttribute)有一个AttributeUsageAttribute应用于它(所有Attribute类都应该如此,但如果没有--请参见下面),那么从BaseAttribute中删除的任何类都应该继承应用到它的AttributeUsage属性。

Derived类从Base继承DerivedAttribute,因为DerivedAttribute没有自己的AttributeUsageAttribute应用于它,因此反射API依赖于BaseAttribute的属性。现在,从BaseAttribute类中去掉AttributeUsageAttribute,得到相同的结果,因为基类System.Attribute类被标记为[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]。因此,任何属性类都将继承此属性,除非指定不同的属性。

哇,这些段落太复杂了。属性上的属性会导致一些繁重的阅读:P

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14955406

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档