小编ant*_*ish的帖子

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(); …
Run Code Online (Sandbox Code Playgroud)

.net c# attributeusage

5
推荐指数
1
解决办法
132
查看次数

标签 统计

.net ×1

attributeusage ×1

c# ×1