gpt4 book ai didi

c# - 继承属性

转载 作者:太空狗 更新时间:2023-10-29 21:40:48 26 4
gpt4 key购买 nike

属性代码

[AttributeUsage(AttributeTargets.Property, Inherited = true)]
class IgnoreAttribute : Attribute
{
}

基类

abstract class ManagementUnit
{
[Ignore]
public abstract byte UnitType { get; }
}

主类

class Region : ManagementUnit
{
public override byte UnitType
{
get { return 0; }
}

private static void Main()
{
Type t = typeof(Region);
foreach (PropertyInfo p in t.GetProperties())
{
if (p.GetCustomAttributes(typeof(IgnoreAttribute), true).Length != 0)
Console.WriteLine("have attr");
else
Console.WriteLine("don't have attr");
}
}
}

输出: 没有属性

解释为什么会这样?毕竟,它必须继承。

最佳答案

The inherited flag dictates whether the attribute can be inherited. The default for this value is false. However, if the inherited flag is set to true, its meaning depends on the value of the AllowMultiple flag. If the inherited flag is set to true and the AllowMultiple flag is false, the attribute will override the inherited attribute. However, if the inherited flag is set to true and the AllowMultiple flag is also set to true, the attribute accumulates on the member.

来自 http://aclacl.brinkster.net/InsideC/32ch09f.htm查看指定继承属性规则一章

编辑:检查 Inheritance of Custom Attributes on Abstract Properties第一个答案:

It's the GetCustomAttributes() method that does not look at parent declarations. It only looks at attributes applied to the specified member.

关于c# - 继承属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10348119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com