c# - 使用反射按声明顺序获取属性

标签 c# reflection properties getproperties

我需要按照类中声明的顺序使用反射获取所有属性。根据 MSDN,使用 GetProperties()

时无法保证顺序

The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order.

但我读到有一种解决方法,可以通过 MetadataToken 对属性进行排序。所以我的问题是,这样安全吗?我似乎无法在 MSDN 上找到任何关于它的信息。或者还有其他方法可以解决这个问题吗?

我当前的实现如下所示:

var props = typeof(T)
   .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
   .OrderBy(x => x.MetadataToken);

最佳答案

在 .net 4.5 上 (and even .net 4.0 in vs2012)您可以使用带有 [CallerLineNumber] 属性的巧妙技巧通过反射做得更好,让编译器为您在您的属性中插入顺序:

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class OrderAttribute : Attribute
{
    private readonly int order_;
    public OrderAttribute([CallerLineNumber]int order = 0)
    {
        order_ = order;
    }

    public int Order { get { return order_; } }
}


public class Test
{
    //This sets order_ field to current line number
    [Order]
    public int Property2 { get; set; }

    //This sets order_ field to current line number
    [Order]
    public int Property1 { get; set; }
}

然后使用反射:

var properties = from property in typeof(Test).GetProperties()
                 where Attribute.IsDefined(property, typeof(OrderAttribute))
                 orderby ((OrderAttribute)property
                           .GetCustomAttributes(typeof(OrderAttribute), false)
                           .Single()).Order
                 select property;

foreach (var property in properties)
{
   //
}

如果您必须处理部分类,您还可以使用 [CallerFilePath] 对属性进行排序。

关于c# - 使用反射按声明顺序获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9062235/

相关文章:

c# - 为什么子类变量先于父类成员变量初始化

scala - 如何对泛型类型参数进行模式匹配?

java - Ant:如何知道十个复制任务中的至少一个复制任务是否真正复制了文件

c# - 循环中处理所有成员

java - 如何获取 java 反射方法对象的 `signature` 字段

java - 安全:http and properties (Spring Security)

php - 从另一个对象向 stdClass 对象添加属性

C# 访问修改后的闭包

c# - 如何知道在 DropDownButton 中点击了什么

c# - 自定义光标异常?