首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >派生类上的C# AllowMultiple属性

派生类上的C# AllowMultiple属性
EN

Stack Overflow用户
提问于 2021-07-14 05:36:33
回答 1查看 330关注 0票数 3

考虑下面的代码片段:

代码语言:javascript
复制
[AttributeUsage(AttributeTargets.Class, AllowMultiple =true)]
public class FooAttribute : Attribute {
    public string Bar { get; set; } 
}

[Foo(Bar = "A")]
public class A{}

[Foo(Bar = "B")]
public class B : A{}

[Foo(Bar = "C")]
public class C : B{}

如果我想得到FooAttribute of class C

代码语言:javascript
复制
var attrList = typeof(C).GetCustomAttributes(typeof(FooAttribute), true) as FooAttribute[];

我会得到所有三个属性。顺序是C,B,A。以下是我的问题:

  • Is这个顺序是一种有保证的行为,这意味着派生类的属性总是出现在比它的基class?
  • Is更小的索引处,因此可以知道属性的特定类型是附加的to?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-14 06:41:36

通常情况下,顺序没有得到保证,编译器将根据平台、区域性和编译器版本产生不同的结果。然而,在这个特定场景中,保证它的顺序是正确的(至少部分)。当您在同一继承级别上分配多个属性时,会出现例外情况:

代码语言:javascript
复制
[AttributeUsage(AttributeTargets.Class, AllowMultiple =true)]
public class FooAttribute : Attribute {
    public string Bar { get; set; } 
}

[Foo(Bar = "A")]
public class A{}

[Foo(Bar = "B"), Foo(Bar = "C")]
public class B : A{}

A(最后)的顺序总是相同的,但B和C可能有所不同: can、-A或B-A。在以下示例中,订单根本没有得到保证:

代码语言:javascript
复制
[Foo(Bar = "A"), Foo(Bar = "B"), Foo(Bar = "C")]
public class A{}

但是,如果将一个属性分配给每个继承级别,则顺序将保持不变。这是由于.NET (框架)中的实现,因为它遍历每个基本类型来收集所有属性(如果是Type.GetCustomAttributes(Type, inherit: true))。这可以在本节代码(System.Private.CoreLibSystem.Reflection)中看到:

代码语言:javascript
复制
private static Attribute[] InternalGetCustomAttributes(EventInfo element, Type type, bool inherit)
{
    [...]

    // walk up the hierarchy chain
    Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);
    if (inherit)
    {
        // create the hashtable that keeps track of inherited types
        Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11);
        // create an array list to collect all the requested attibutes
        List<Attribute> attributeList = new List<Attribute>();
        CopyToArrayList(attributeList, attributes, types);

        EventInfo? baseEvent = GetParentDefinition(element);
        while (baseEvent != null)
        {
            attributes = GetCustomAttributes(baseEvent, type, false);
            AddAttributesToList(attributeList, attributes, types);
            baseEvent = GetParentDefinition(baseEvent);
        }
        Attribute[] array = CreateAttributeArrayHelper(type, attributeList.Count);
        attributeList.CopyTo(array, 0);
        return array;
    }
    else
        return attributes;
}

请注意,这是针对events的,但对于MemberInfo (Type)也是如此。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68372586

复制
相关文章

相似问题

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