考虑以下情况:
BaseAttribute有一个指定不可继承的AttributeUsageAttribute (Inherited = False)。DerivedAttribute继承自该基属性类。Base应用了派生属性。Derived被要求提供它的自定义属性,包括继承属性(inherit: true)。以下是相应的代码:
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.aspx说AttributeUsageAttribute本身是可继承的。
现在,这是一个bug,还是被期望/记录在某个地方?
注(2013-02-20):实验表明,BaseAttribute类的AttributeTargets部分确实是由DerivedAttribute类继承的。例如,当我将BaseAttribute上允许的目标更改为AttributeTargets.Method时,C#编译器将不允许我将DerivedAttribute应用于类。因此,Inherited = false部分不被DerivedAttribute继承是没有意义的,因此我倾向于考虑GetCustomAttributes实现中的一个bug。
发布于 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
https://stackoverflow.com/questions/14955406
复制相似问题