私はクラスのプロパティに適用するカスタム属性を持っています。この属性は、クラスのプロパティをフラットファイルにエクスポートするために使用されます。C#カスタムプロパティ属性を使用してクラスのプロパティを並べ替える方法
属性のプロパティの1つは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
}
}
UPDATE:私はあなたが正しい属性を持つプロパティをフィルタリングするために、各PropertyInfoにGetCustomAttributes()メソッドを使用することができ、その後、残りを並べ替える必要があります
単なる考えですが、シンプルなxmlシリアル化を行い、シンプルなフラットXMLをフラットファイルに変換するライブラリを作成する方が簡単かもしれません。これは再利用可能で、このカスタム属性設定作業と反映をすべてスキップできます。 – asawyer