我有適用於類的屬性的自定義屬性。該屬性用於將類的屬性導出到平面文件。C#如何使用自定義屬性屬性對類進行排序
其中一個屬性的屬性是FieldOrder。我需要確保我導出類的屬性的順序是正確的。此外,並非所有類上的屬性都具有自定義屬性。
我發現此文章:How do I sort a generic list based on a custom attribute?此解決方案假定所有屬性都具有自定義屬性,這不是我的情況。我也希望能有更優雅的解決方案。
非常感謝您的幫助!
public interface IFileExport{}
public class ExportAttribute: Attribute
{
public int FieldOrder { get; set; }
public int FieldLength { get; set; }
public ExportAttribute() { }
}
public class ExportClass: IFileExport
{
[ExportAttribute(FieldOrder = 2, FieldLength = 25)]
public string LastName { get; set; }
[ExportAttribute(FieldOrder=1, FieldLength=25)]
public string FirstName { get; set; }
[ExportAttribute(FieldOrder = 3, FieldLength = 3)]
public int Age { get; set; }
public ExportClass() { }
}
public class TestClass
{
public static List<PropertyInfo> GetPropertiesSortedByFieldOrder(IFileExport fileExport)
{
//get all properties on the IFileExport object
PropertyInfo[] allProperties = fileExport.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
//now I need to figure out which properties have the ExportAttribute and sort them by the ExportAttribute.FieldOrder
}
}
更新:我訂購的ExportAttribute.FieldOrder升序屬性
只是一個想法,但也許它會更容易做一個簡單的XML序列化,然後編寫一個庫,將簡單的平板XML轉換爲平面文件。它可以重用,並且可以跳過所有這些自定義屬性設置工作和反射。 – asawyer