是否可以在声明顺序(或任何其他顺序)中获取<t>的所有属性?</t>

时间:2014-06-13 20:03:03

标签: c# generics reflection properties

按顺序获取类的属性,我尝试使用Attribute并且没问题:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public sealed class MyAttribute: Attribute
{
    public int Index { get; set; }
}

public class AnyClass
{
    [Campo(Index = 2)]
    public int Num { get; set; }

    [Campo(Index  = 0)]
    public string Name { get; set; }

    [Campo(Index = 1)]
    public DateTime EscDate { get; set; }
}

// then I get properties in order
var props = (from pro in (new AnyClass()).GetType().GetProperties()
             let att = pro.GetCustomAttributes(false).Cast<MyAttribute>().First()
             let order = att.Index
             orderby order ascending
             select pro).ToArray();
// result:
// string   Name
// DateTime EscDate
// int      Num

但是,当<T>未知时,是否有可能获得它们

var props = typeof(T).GetProperties(); // ... order here!

执行此操作时,并不总是相同的顺序,如果您不知道<T>是否具有属性,如何设置?,还有其他方法吗?

1 个答案:

答案 0 :(得分:1)

您无法获得声明顺序(即它们在代码中的顺序),因为在编译代码时不会保存该声明顺序。如果您只需要一个一致的订单,只需按属性名称排序:

var props = (from pro in typeof(T).GetProperties()
             orderby pro.Name
             select pro).ToArray();

如果您想使用MyAttribute,可以执行以下操作:

var pairs = (from pro in typeof(T).GetProperties()
             let att = pro.GetCustomAttributes(false)
                          .Cast<MyAttribute>().FirstOrDefault()
             select new { pro, att }).ToList();
IList<PropertyInfo> props;
if (pairs.All(x => x.att != null))
    props = (from pair in pairs
             let order = pair.att.Index
             orderby order ascending
             select pair.pro).ToList();
else
    props = (from pair in pairs
             orderby pair.pro.Name
             select pair.pro).ToList();