1

これが特にカスタム属性を必要とするかどうかはわかりませんが、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. この (または同様の) 機能を取得するにはどうすればよいですか。
4

1 に答える 1

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));
于 2013-01-04T21:35:29.090 に答える