前一陣子,當我有我寫了同樣的問題,一個輔助類基於該Order
屬性進行排序屬性的屬性。我使用了內置的DisplayAttribute
,但您只需將Order
屬性添加到您編寫的任何屬性即可。
class FieldSorter : IComparer, IComparer<DisplayAttribute>, IEqualityComparer<DisplayAttribute>
{
public int Compare(object x, object y)
{
return Compare((DisplayAttribute)x, (DisplayAttribute)y);
}
public int Compare(DisplayAttribute x, DisplayAttribute y)
{
return x.Order.CompareTo(y.Order);
}
public bool Equals(DisplayAttribute x, DisplayAttribute y)
{
return Compare(x, y) == 0;
}
public int GetHashCode(DisplayAttribute obj)
{
return obj.GetHashCode();
}
public static SortedList<DisplayAttribute, PropertyInfo> GetSortedFields(Type type)
{
PropertyInfo[] props = type.GetProperties();
var sortedProps = new SortedList<DisplayAttribute, PropertyInfo>(props.Length, new FieldSorter());
object[] atts;
int assignedOrder = 1000; // anything without pre-assigned order gets a ridiculously high order value. same for duplicates.
foreach (var prop in props)
{
atts = prop.GetCustomAttributes(typeof(DisplayAttribute), true);
if (atts.Length > 0)
{
var att = (DisplayAttribute)atts[0];
if (!att.GetOrder().HasValue || sortedProps.Keys.Contains(att, new FieldSorter()))
att.Order = assignedOrder++;
sortedProps.Add(att, prop);
}
}
return sortedProps;
}
}
這給你一個SortedList
其中關鍵是屬性和值是的PropertyInfo。這是因爲我仍然需要訪問屬性的其他屬性。
用法示例:
public class Stats
{
[Display(Name = "Changes", Description = "Changed records.", Order = 8)]
public int RecordsWithChanges { get; set; }
[Display(Name = "Invalid", Description = "Number of invalid records analyzed.", Order = 4)]
public int InvalidRecordCount { get; set; }
[Display(Name = "Valid", Description = "Number of valid records.", Order = 6)]
public int ValidRecordCount { get; set; }
[Display(Name = "Cost", Description = "Number of records with a Cost value.", Order = 10)]
public int RecordsWithCost { get; set; }
public Stats(int changed, int valid, int invalid, int cost)
{
RecordsWithChanges = changed;
ValidRecordCount = valid;
InvalidRecordCount = invalid;
RecordsWithCost = cost;
}
}
class Program
{
static void Main(string[] args)
{
var foo = new Stats(123, 456, 7, 89);
var fields = FieldSorter.GetSortedFields(foo.GetType());
foreach (DisplayAttribute att in fields.Keys)
Console.WriteLine("{0}: {1} ({2}) == {3}",
att.Order, att.Name, att.Description, fields[att].GetValue(foo, null));
null));
}
}
輸出:
4: Invalid (Number of invalid records analyzed.) -- 7
6: Valid (Number of valid records.) -- 456
8: Changes (Changed records.) -- 123
10: Cost (Number of records with a Cost value.) -- 89
你在做什麼,其中的順序是有意義? –
爲第三方創建的文件需要採用特定的格式。 – Andy