考虑下面的代码片段:
[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
var attrList = typeof(C).GetCustomAttributes(typeof(FooAttribute), true) as FooAttribute[];我会得到所有三个属性。顺序是C,B,A。以下是我的问题:
。
发布于 2021-07-14 06:41:36
通常情况下,顺序没有得到保证,编译器将根据平台、区域性和编译器版本产生不同的结果。然而,在这个特定场景中,保证它的顺序是正确的(至少部分)。当您在同一继承级别上分配多个属性时,会出现例外情况:
[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。在以下示例中,订单根本没有得到保证:
[Foo(Bar = "A"), Foo(Bar = "B"), Foo(Bar = "C")]
public class A{}但是,如果将一个属性分配给每个继承级别,则顺序将保持不变。这是由于.NET (框架)中的实现,因为它遍历每个基本类型来收集所有属性(如果是Type.GetCustomAttributes(Type, inherit: true))。这可以在本节代码(System.Private.CoreLib,System.Reflection)中看到:
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)也是如此。
https://stackoverflow.com/questions/68372586
复制相似问题