これが私が持っているクラスの簡単な見方です:
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; }
}