gpt4 book ai didi

c# - GetCustomAttributes 继承参数与 AttributeUsage.Inherited

转载 作者:行者123 更新时间:2023-11-30 16:42:37 27 4
gpt4 key购买 nike

为什么不GetCustomAttributes(true)返回属性 AttributeUsageAttribute.Inherited = false ?在我看到的文档中没有任何内容表明这两者应该相互作用。以下代码输出 0

class Program
{

[AttributeUsage(AttributeTargets.Class, Inherited = false)]
class NotInheritedAttribute : Attribute { }

[NotInherited]
class A { }

class B : A { }

static void Main(string[] args)
{
var attCount = typeof(B).GetCustomAttributes(true).Count();
Console.WriteLine(attCount);
}
}

最佳答案

Type.GetCustomAttributes()是调用 Attribute.GetCustomAttributes() 的扩展方法依次调用 GetCustomAttributes 并将参数 inherit 设置为 true。所以默认情况下,您在使用 GetCustomAttributes() 时就已经继承了。

所以唯一的区别是 GetCustomAttributes()GetCustomAttributes(inherit: false)。后者将禁用可继承属性的继承,而前者只会传递那些可继承的属性。

您不能强制将本身不可继承的属性设为可继承。

有关快速摘要,请参阅以下示例:

void Main()
{
typeof(A).GetCustomAttributes().Dump(); // both
typeof(A).GetCustomAttributes(inherit: false).Dump(); // both

typeof(B).GetCustomAttributes().Dump(); // inheritable
typeof(B).GetCustomAttributes(inherit: false).Dump(); // none because inheritance is prevented

typeof(C).GetCustomAttributes().Dump(); // both
typeof(C).GetCustomAttributes(inherit: false).Dump(); // both because C comes with its own copies
}

[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public class InheritableExampleAttribute : Attribute { }

[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class NonInheritableExampleAttribute : Attribute { }

[InheritableExample]
[NonInheritableExample]
public class A { }

public class B : A { }

[InheritableExample]
[NonInheritableExample]
public class C : A { }

关于c# - GetCustomAttributes 继承参数与 AttributeUsage.Inherited,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46487663/

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