在.net 4.5 (甚至vs2012中的.net
4.0)上,您可以使用带有
[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]。



