用于指定显示格式的自定义属性

时间:2013-01-04 18:52:31

标签: c# string-formatting custom-attributes

首先我要说的是,我不知道这个需要一个自定义属性,但DisplayFormatAttribute最接近我想要的意图。

<小时/> 我想要的是什么

我希望能够为类的属性指定字符串格式,如下所示:

public class TestAttribute
{
    [CustomDisplayFormatAttribute(DataFormatString = "{0}")]
    public int MyInt { get; set; }

    [CustomDisplayFormatAttribute(DataFormatString = "{0:0.000}")]
    public float MyFloat { get; set; }

    [CustomDisplayFormatAttribute(DataFormatString = "{0:0.0}")]
    public float MyFloat2 { get; set; }

    [CustomDisplayFormatAttribute(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime MyDateTime { get; set; }
}

......并且能够像这样使用它:

TestAttribute t = new TestAttribute()
        {
            MyDateTime = DateTime.Now,
            MyFloat = 1.2345678f,
            MyFloat2 = 1.2345678f,
            MyInt = 5
        };
Console.WriteLine(t.MyDateTime.ToFormattedString());
Console.WriteLine(t.MyFloat.ToFormattedString());
Console.WriteLine(t.MyFloat2.ToFormattedString());
Console.WriteLine(t.MyInt.ToFormattedString());

<小时/> 我到目前为止做了什么

我已成功创建了自定义属性CustomDisplayFormatAttribute并已将其应用于我的元素,但是如果不了解我的TestAttribute类,我无法获取该属性。

我的第一个想法是使用扩展方法来处理它,因此ToFormattedString()函数。

话虽如此,理想情况下,我可以调用类似ToFormattedString()的函数,并让它处理查找显示格式并将值应用于它。

<小时/> 我的问题

  1. 这是否可以使用C#
  2. 我如何获得此(或类似)功能。

1 个答案:

答案 0 :(得分:2)

当您使用TestAttribute方法时,无法检索ToFormattedString()类或其属性。另一种方法是将方法传递给额外的参数,该参数是获取属性的表达式。我听说处理Linq表达式很昂贵,你需要测试一下你的情况是否正确:

public interface IHaveCustomDisplayFormatProperties
{
}

public class TestAttribute : IHaveCustomDisplayFormatProperties
{
    [CustomDisplayFormatAttribute(DataFormatString = "{0}")]
    public int MyInt { get; set; }

    [CustomDisplayFormatAttribute(DataFormatString = "{0:0.000}")]
    public float MyFloat { get; set; }

    [CustomDisplayFormatAttribute(DataFormatString = "{0:0.0}")]
    public float MyFloat2 { get; set; }

    [CustomDisplayFormatAttribute(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime MyDateTime { get; set; }
}

public static class IHaveCustomDisplayFormatPropertiesExtensions
{
    public static string FormatProperty<T, U>(this T me, Expression<Func<T, U>> property)
        where T : IHaveCustomDisplayFormatProperties
    {
        return null; //TODO: implement
    }
}

可以像这样使用:

TestAttribute t = new TestAttribute()
{
    MyDateTime = DateTime.Now,
    MyFloat = 1.2345678f,
    MyFloat2 = 1.2345678f,
    MyInt = 5
};
Console.WriteLine(t.FormatProperty(x => x.MyDateTime));
Console.WriteLine(t.FormatProperty(x => x.MyFloat));
Console.WriteLine(t.FormatProperty(x => x.MyFloat2));
Console.WriteLine(t.FormatProperty(x => x.MyInt));