これが特にカスタム属性を必要とするかどうかはわかりませんが、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()
て、表示形式を調べて値を適用できるようにすることができます。
私の質問
- これはC#を使用して可能ですか
- この (または同様の) 機能を取得するにはどうすればよいですか。