2011-09-30 5 views
14

実行時に割り当てられるタイプにオブジェクトを変換したいと思います。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); 
} 
+0

これを使用する例を挙げることができますか?具体的なタイプがわからない場合は、なぜそれをキャストする必要がありますか?ダイナミックになると思いましたか? – Carsten

+0

'Foo'メソッドに引数を渡すときの型が分かりますか? –

+0

@JamesJohnson私は、あなたがいつも必要なのかを知ることができると思う:-) – username

答えて

28

あなたは(入力が同じように簡単にオブジェクト可能性が...私は単なる文字列バージョンプリベークを持っていた)Convert.ChangeType(...)関数を使用する必要があります。

/// <summary> 
/// Sets a value in an object, used to hide all the logic that goes into 
///  handling this sort of thing, so that is works elegantly in a single line. 
/// </summary> 
/// <param name="target"></param> 
/// <param name="propertyName"></param> 
/// <param name="propertyValue"></param> 
public static void SetPropertyValueFromString(this object target,    
           string propertyName, string propertyValue) 
{ 
    PropertyInfo oProp = target.GetType().GetProperty(propertyName); 
    Type tProp = oProp.PropertyType; 

    //Nullable properties have to be treated differently, since we 
    // use their underlying property to set the value in the object 
    if (tProp.IsGenericType 
     && tProp.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) 
    { 
     //if it's null, just set the value from the reserved word null, and return 
     if (propertyValue == null) 
     { 
      oProp.SetValue(target, null, null); 
      return; 
     } 

     //Get the underlying type property instead of the nullable generic 
     tProp = new NullableConverter(oProp.PropertyType).UnderlyingType; 
    } 

    //use the converter to get the correct value 
    oProp.SetValue(target, Convert.ChangeType(propertyValue, tProp), null); 
} 
+0

このアプローチの唯一の欠点は、ヌル可能な型では動作しないことです。 –

+0

nullable型のロジックがあることに気がつきました。 –

+0

Convert.ChangeType()は満足していますが、enums、tnx fordarehのチェックを行う必要があります。 – nAviD

2

ユニバーサルタイプコンバータはあなたが探しているものですか?また

NuGet Install-Package UniversalTypeConverter

Universal Type Converter

することができますが、ここでは問題外Genericsを使用している:簡単な偉業..

は、このアプローチを試してみませんか?変換の目標タイプが少なくとも分かっている場合は、その解決策を促進します。

0

私は「それが動作分からないが、それを試してみる:

public static T To<T>(this IConvertible obj) 
{ 
    return (T)Convert.ChangeType(obj, typeof(T)); 
} 

Public void Foo(object obj,string propertyName,object value) 
{ 
    Type t= obj.GetType().GetProperty(propName).PropertyType; 
    obj.GetType().GetProperty(propName).SetValue(obj, value.To<t>(), null); 
} 
+0

To ()のジェネリック型tはコンパイル時に定義する必要があるため、機能しません。 – nAviD

+0

@Navid:いいえ、私の答えの始めに置いた拡張方法のためです。私はそれが実行時に評価されることを確信しています... – Marco

+0

これはうまく動作せず、@ Navidが正しいという事実を言うことができます。一般的なメソッドはコンパイル時に型を提供する必要があります – workabyte

1

は、ここであなたがそれを行うことができます別の方法ですが、私は、ジェネリック型のサポートがなければわから

ないよ:

ジェネリック型をサポートしているため
public void Foo(object obj,string propertyName,object value) 
{ 
    //Getting type of the property og object. 
    Type type = obj.GetType().GetProperty(propertyName).PropertyType; 

    obj.GetType().GetProperty(propertyName).SetValue(obj, Activator.CreateInstance(type, value), null); 
} 

public void Foo(object obj,string propertyName,object value) 
{ 
    //Getting type of the property og object. 
    Type type = obj.GetType().GetProperty(propertyName).PropertyType; 

    if (type.IsGenericType) 
     type = type.GetGenericArguments()[0]; 

    obj.GetType().GetProperty(propertyName).SetValue(obj, Activator.CreateInstance(type, value), null); 
} 
0

私はC#で変換機能を使用していました。私は私の変換をやっている方法は、リフレクションを使用しています。:

Type type = this.myObject.GetType(); 

if (type.Name == "MyObjectClass") { 
var Voucherrequest = (MyObjectClass)Convert.ChangeType(myObject, typeof(MyObjectClass)); 

これは、すべてあなたがに変換したいどのような種類を知っていると仮定しています。スイッチを作ったり、複数のタイプを反映させたりすることもできます。

関連する問題