3

環境:asp.net fx3.5

与えられた

public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public decimal UnitPrice { get; set; }
}

私はList<Product>コレクションを持っています。

作成しているcsvファイルのヘッダー行にしたいので、プロパティ名を取得する方法はありますか?

だから私が探している結果はstring = "ProductId,ProductName,UnitPrice"

4

3 に答える 3

4
var headers = this.GetType().GetProperties().Select(p => p.Name).Aggregate((p1, p2) => p1 + "," + p2);
于 2012-05-26T00:11:06.667 に答える
2

次のクラスを使用できますTypeDescriptor(プレーンリフレクションよりも効率的です)。

string.Join(",", TypeDescriptor.GetProperties(instance).Select(p => p.Name))
于 2012-05-26T00:16:14.303 に答える
1
String.Join(",", typeof(Product).GetProperties().Select(p => p.Name))

Linqを使用したくない場合は、GetPropertiesによって返されるPropertyInfo配列を反復処理し、名前を文字列に連結することができます。

于 2012-05-26T00:11:52.570 に答える