Type.GetCustomAttributes<;TA属性>;以随机顺序返回自定义属性
本文关键字:顺序 随机 返回 自定义属性 属性 GetCustomAttributes lt TA Type gt | 更新日期: 2024-09-21 23:31:58
考虑以下代码:
[AttributeUsage(AttributeTargets.Class)]
public sealed class SampleAttribute : Attribute
{
public String Name {get;set};
public SampleAttribute(String testName)
{
Name = testName;
}
}
[SampleAttribute("A")]
[SampleAttribute("B")]
public class Test
{
}
var attributes = typeof(Test).GetCustomAttributes<SampleAttribute>();
不幸的是,方法"GetCustomAttributes"以随机顺序返回属性。
例如,以下代码将在每次运行应用程序时打印不同的结果。
foreach(var att in attributes)
{
Console.WriteLine(att.Name);
}
准时,先用"A",然后用"B",反之亦然。
我的问题有解决办法吗?
我不会添加订单之类的列,我想解决这个问题。
环境:.NET 4.5.1、Visual Studio 2012 Update 3 SDK、C#5。调试和发布模式。
我认为文档中没有任何内容可以保证自定义属性将以任何特定顺序返回。如果需要有序的属性,请将Order
成员添加到属性类中。