6

これが私が持っているクラスの簡単な見方です:

public class SalesMixRow
{
    [DisplayFormat(DataFormatString = "{0:c0}")]
    public decimal? DelSales { get; set; }
}

Webアプリのかみそりビューでは、次の形式でその値を取得できます。

@Html.DisplayFor(model => model.DelSales)

この値も出力する必要があるコンソールアプリがあります。DataFormatStringをどこにも繰り返さずにコンソールアプリに出力するにはどうすればよいですか?

更新:リフレクションを使用するというアイデアが好きです。それは、私が個別に尋ねようとしていた質問を解決するからです。これは完全な作業サンプルです。文字列パスでプロパティを取得し、可能な場合はDisplayFormatで出力します。

void Main()
{
    var model = new SmrDistrictModel
    {
        Title = "DFW",
        SalesMixRow = new SalesMixRow
        {
            DelSales = 500m
        }
    };

    Console.WriteLine(FollowPropertyPath(model, "Title"));
    Console.WriteLine(FollowPropertyPath(model, "SalesMixRow.DelSales"));
}

public static object FollowPropertyPath(object value, string path)
{
    Type currentType = value.GetType();
    DisplayFormatAttribute currentDisplayFormatAttribute;
    string currentDataFormatString = "{0}";

    foreach (string propertyName in path.Split('.'))
    {
        PropertyInfo property = currentType.GetProperty(propertyName);
        currentDisplayFormatAttribute = (DisplayFormatAttribute)property.GetCustomAttributes(typeof(DisplayFormatAttribute), true).FirstOrDefault();
        if (currentDisplayFormatAttribute != null)
        {
            currentDataFormatString = currentDisplayFormatAttribute.DataFormatString;
        }
        value = property.GetValue(value, null);
        currentType = property.PropertyType;
    }
    return string.Format(currentDataFormatString, value);
}

public class SmrDistrictModel
{
    public string Title { get; set; }
    public SalesMixRow SalesMixRow { get; set; }
}

public class SalesMixRow
{
    [DisplayFormat(DataFormatString = "{0:c0}")]
    public decimal? DelSales { get; set; }
}
4

2 に答える 2

10

リフレクションを使用して、クラスから属性を取得できます。次に、属性からフォーマット文字列を取得し、を使用して適用しますstring.Format

SalesMixRow instance = new SalesMixRow { DelSales=1.23 };

PropertyInfo prop = typeof(SalesMixRow).GetProperty("DelSales");
var att = (DisplayFormatAttribute)prop.GetCustomAttributes(typeof(DisplayFormatAttribute), true).FirstOrDefault();
if (att != null)
{
    Console.WriteLine(att.DataFormatString, instance.DelSales);
}

(属性System.ComponentModel.DataAnnotations.dllを含むアセンブリを追加する必要があることに注意してください。)DisplayFormat

于 2012-11-18T19:22:55.157 に答える
0

私のDisplayFormat経験では、MVCアプリケーションを対象としています。コンソールアプリケーションの場合、を介して利用できる非常に洗練された表示フォーマットシステムがありますString.Format。詳細については、このリンクを参照してください

あなたの場合、あなたはこのように書くことができます

Console.WriteLine(string.Format("0:c0", SalesMixRow.DataSales));
于 2012-11-18T19:27:16.790 に答える