実行時に割り当てられるタイプにオブジェクトを変換したいと思います。C#.NETでタイプをオンザフライに変換する
たとえば、文字列値(0)をObject.Property
に割り当てる関数があるとします。
どのように値を適切なタイプに変換しますか?たとえば、整数、文字列、列挙型などです。
Public void Foo(object obj,string propertyName,object value)
{
//Getting type of the property og object.
Type t= obj.GetType().GetProperty(propName).PropertyType;
//Now Setting the property to the value .
//But it raise an error,because sometimes type is int and value is "2"
//or type is enum (e.a: Gender.Male) and value is "Male"
//Suppose that always the cast is valid("2" can be converted to int 2)
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}
これを使用する例を挙げることができますか?具体的なタイプがわからない場合は、なぜそれをキャストする必要がありますか?ダイナミックになると思いましたか? – Carsten
'Foo'メソッドに引数を渡すときの型が分かりますか? –
@JamesJohnson私は、あなたがいつも必要なのかを知ることができると思う:-) – username