【问题标题】:Attribute inheritance on properties fails in C#属性的属性继承在 C# 中失败
【发布时间】:2019-12-08 20:31:35
【问题描述】:

我有以下属性,其中 Inherited 设置为 true。

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, Inherited = true)]
public class InheritedAttribute : Attribute { }

DerivedA 类包含一个属性,该属性使用[InheritedAttribute] 标记覆盖 BaseA 的虚拟属性。

public class BaseA
{
    [InheritedAttribute]
    public virtual int prop { get; set; }
}

public class DerivedA : BaseA
{
    public override int prop { get; set; }
}

很遗憾,DerivedA.prop 上没有找到该属性,因此该属性还没有被继承到子属性。

public static void Main()
{
    var propertyInfo = typeof(DerivedA).GetProperties()[0];
    // propertyInfo.CustomAttributes is empty
    // propertyInfo.GetCustomAttributes(true) is empty
}

如果属性被放置在方法而不是属性上,如example code on microsoft's website 中所示,则该属性将按预期继承,并将在methodInfo.CustomAttributes 中找到。

属性继承是不允许的吗?还是我完全错过了其他东西?

【问题讨论】:

  • 只是一个想法:属性的某些属性不是在属性级别上实现的,而是在 Getter 和 Setter 级别上实现的。你能检查propertyInfo.GetGetMethod.GetCustomAttributes(true)。由于这是一种方法,并且方法应该按照描述的方式工作,也许就是这样。 (GetSetMethod 也一样)

标签: c# .net properties


【解决方案1】:

根据 MSDN 规范,这是因为 GetCustomAttributes 方法忽略了属性和事件的 inherit 参数。其实你的属性有这个属性,你可以调用Attribute.GetCustomAttributes方法查看,推荐

var propertyInfo = typeof(DerivedA).GetProperties()[0];
var attributes = Attribute.GetCustomAttributes(propertyInfo);

【讨论】:

    【解决方案2】:

    嗯,这种行为很奇怪。但是有这样的解决方法:

     var c = propertyInfo.GetCustomAttribute(typeof(InheritedAttribute), true);
    

    哪个是直接指定的。

    【讨论】:

    • 此方法忽略属性和事件的inherit 参数
    • @PavelAnikhouski 对于GetCustomAttributes 是正确的,而不是对于GetCustomAttribute,但我更喜欢您的解决方案,因为操作想要获取属性
    最近更新 更多