这是我所拥有的课程的简化视图:
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; }
}