小编pig*_*Bot的帖子

属性上的属性继承在 C# 中失败

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

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

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

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

public class DerivedA : BaseA
{
    public override int prop { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,在 上找不到DerivedA.prop该属性,因此该属性尚未继承到子属性。

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

如果属性被放置在方法而不是属性上,如微软网站上示例代码所示,该属性将按预期继承,并将在methodInfo.CustomAttributes …

.net c# properties

3
推荐指数
1
解决办法
131
查看次数

标签 统计

.net ×1

c# ×1

properties ×1