次のシナリオを検討してください。
- 基本属性クラスには、継承可能ではない
BaseAttributeという指定があります ( )。AttributeUsageAttributeInherited = 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
{
}
}
このシナリオでは、GetCustomAttributesAPI はDerivedAttributeクラスのインスタンスを返します。http://msdn.microsoft.com/en-us/library/system.attributeusageattribute.aspxAttributeUsageAttributeはそれ自体が継承可能であると述べているため、そのインスタンスが返されないと予想していました。
さて、これはバグですか、それとも予想される/どこかに文書化されていますか?
注 (2013-02-20):実験AttributeTargetsでは、クラスの一部BaseAttributeが実際にクラスによって継承されることが示されていDerivedAttributeます。たとえば、許可されたターゲットを に変更するBaseAttributeと、C# コンパイラはクラスAttributeTargets.Methodへの適用を許可しません。DerivedAttributeしたがって、そのInherited = false部分が に継承されないということは意味がなくDerivedAttribute、 の実装にバグがあると考えがちですGetCustomAttributes。