首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GetCustomAttributes继承参数与AttributeUsage.Inherited

GetCustomAttributes继承参数与AttributeUsage.Inherited
EN

Stack Overflow用户
提问于 2017-09-29 11:13:49
回答 1查看 2.5K关注 0票数 4

为什么GetCustomAttributes(true)不返回AttributeUsageAttribute.Inherited = false(AttributeUsageAttribute.Inherited = false)的属性(https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(System.AttributeUsageAttribute.Inherited%29;k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.6.1%29;k(DevLang-csharp%29&rd=true)?文档中没有提到这两者应该相互作用的东西)。下面的代码输出0

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

发布于 2017-09-29 11:29:07

Type.GetCustomAttributes()是一个扩展方法,它调用Attribute.GetCustomAttributes(),然后调用参数inherit设置为trueGetCustomAttributes。因此,默认情况下,在使用GetCustomAttributes()时,您已经在继承。

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

不能强制本身不可继承的属性是可继承的.

请参阅下面的示例以获得快速摘要:

代码语言:javascript
复制
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 { }
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46487663

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档