简体   繁体   中英

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:

[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

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?

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:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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