You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

继承特性中AttributeUsage表现异常,这是预期行为吗?

自定义特性基类的AttributeUsage中Inherited属性未被继承的问题分析

我在开发带有公共基类的自定义特性时,仅在抽象基特性类TestAttributeBase上声明了AttributeUsage特性,设置为AttributeTargets.Class, AllowMultiple = true, Inherited = true。但实际使用具体特性TestAttribute时发现:它继承了基类的Target和AllowMultiple设置,却未继承Inherited属性——调用typeof(B).GetCustomAttributes<TestAttributeBase>(true)仅返回2个特性(预期是3个),只有给TestAttribute也添加完全相同的AttributeUsage配置,才能得到预期的3个结果。

问题复现代码

[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;  // 注:原代码存在笔误,已修正为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); // 实际输出2,预期输出3
}

原因解析

这是.NET特性系统的设计行为,具体规则如下:

  • AttributeUsage的Targets和AllowMultiple属于编译时约束,编译器会强制子类特性继承这些设置(比如将基类Targets改为Field,子类特性标注在Class上会直接编译报错;基类AllowMultiple设为false,子类特性重复标注也会编译报错)。
  • 而Inherited是运行时行为控制,它决定特性是否会被派生类继承。对于未显式声明AttributeUsage的自定义特性子类,.NET会默认将其Inherited设为false,完全忽略基类的Inherited设置。

你的测试代码中,TestAttribute因未显式设置AttributeUsage,其Inherited实际为默认的false,导致类A上的TestAttribute("A")不会被类B继承,最终只能拿到B自身的2个特性。当给TestAttribute显式添加Inherited = true的AttributeUsage后,特性继承规则生效,就能得到预期的3个结果。

内容的提问来源于stack exchange,提问作者antifish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 09:35:36