如何在控制台应用程序中应用DisplayFormat DataFormatString输出属性(理想情况下按字符串查询对象)?

Chr*_*ris 5 asp.net reflection asp.net-mvc console-application razor

这是我所拥有的课程的简化外观:

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

在Web应用程序剃须刀视图中,我可以使用以下格式获取该值:

@Html.DisplayFor(model => model.DelSales)
Run Code Online (Sandbox Code Playgroud)

我有一个控制台应用程序,也需要输出此值.如何在控制台应用程序中输出它而无需在任何地方重复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; }
}
Run Code Online (Sandbox Code Playgroud)

McG*_*gle 9

您可以使用反射从类中检索属性.然后从属性中获取格式字符串,并使用它来应用它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);
}
Run Code Online (Sandbox Code Playgroud)

(请注意,您需要添加System.ComponentModel.DataAnnotations.dll包含该DisplayFormat属性的程序集.)