简体   繁体   English

是否有可能获得的所有属性 <T> 按照他们的申报顺序(或其他顺序)?

[英]Is it possible to get all properties of <T> in their declaration order (or any other order)?

Getting properties of a class in order, I've tried with Attribute and is ok: 按顺序获取类的属性,我尝试使用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

but, is it possible to get them, when <T> is unknown 但是,当<T>未知时,是否有可能获得它们

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

When doing this, not always is the same order, how to set it if you don't know that <T> has attributes or not?, is there any other method? 当执行此操作时,顺序不一定总是相同的,如果您不知道<T>是否具有属性,如何设置它呢?还有其他方法吗?

You can't get the declaration order (ie the order they are in the code), since that's not saved when the code is compiled. 您无法获得声明顺序(即它们在代码中的顺序),因为在编译代码时不会保存该声明顺序。 If all you need is a consistent order, just order by the property name: 如果您只需要一个一致的订单,只需按属性名称排序即可:

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

If you want to use MyAttribute if it's there, you might do something like this: 如果要使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM