ant*_*ish 5 .net c# attributeusage
我正在使用自定义属性,它们也有一个公共基类。AttributeUsage 属性是在基属性类上声明的,而不是在具体属性类上声明的。我在基类上的属性用法说
AttributeTargets.Class, AllowMultiple = true, Inherited = true
现在,当我使用具体属性类时,他们使用 Target 和 AllowMultiple 的基属性类中的 AttributeUsage 设置,但不使用 Inherited -> 这对我来说没有任何意义。
这是一个小代码示例,它没有输出我期望的结果:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public abstract class TestAttributeBase : Attribute
{
}
public class TestAttribute : TestAttributeBase
{
public string Value {get; private set;}
public TestAttribute(string value)
{
Value = Value;
}
}
[TestAttribute("A")]
public class A {
}
[TestAttribute("B")]
[TestAttribute("C")]
public class B : A
{
}
public static void Main()
{
var customAttributes = typeof(B).GetCustomAttributes<TestAttributeBase>(true).ToList();
Console.WriteLine(customAttributes.Count);
}
Run Code Online (Sandbox Code Playgroud)
这是具有相同代码的 dotnetfiddle 链接:https ://dotnetfiddle.net/BZ7R4S
如果运行此代码,它会输出“2”,但我期望“3”。of[AttributeUsage]肯定TestAttributeBase会继承到 the TestAttribute,因为如果更改AttributeTargets.Class为 eg AttributeTargets.Field,代码将无法编译。如果你设置的AllowMultiple代码false不编译 -> 我从中看出它[AttributeUsage]被继承到具体Attribute类,但不是Inherited属性。
这有意义吗?
如果我将完全相同的内容添加[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]到混凝土中TestAttribute,它就会起作用并输出 3
即使听起来像是一个修复此问题的错误,但现在可能已经相当破坏了,因为从一开始就是这样。鉴于有一个解决方法:添加您自己的
[AttributeUsage]而不是假设将使用基类按计划关闭问题
因此唯一的选择是将属性应用于派生类:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class TestAttribute : TestAttributeBase
{
// ...
}
Run Code Online (Sandbox Code Playgroud)