24

代替タイトル:実行時に型に動的に変換します。

オブジェクトを、実行時に割り当てられる型に変換したいと考えています。

TextBox or Dropdownlistたとえば、文字列値 ( から) を に代入する関数があるとし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);
}
4

5 に答える 5

44

Convert.ChangeType(...) 関数を使用する必要があります [注: 以下の関数では、入力された propertyValue は簡単にオブジェクト型である可能性があります ... 文字列バージョンを事前に作成しました]:

/// <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);
}
于 2011-09-30T21:21:07.003 に答える
2

あなたが求めているのはユニバーサル型コンバーターです!? 簡単な偉業ではありません..

このアプローチを試してください:

ユニバーサルタイプコンバータ

NuGetでできますInstall-Package UniversalTypeConverter

また、Genericsここでの使用は問題外ですか?少なくとも変換のターゲット タイプがわかっている場合は、ソリューションが容易になります。

于 2011-09-30T21:20:09.997 に答える
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);
} 
于 2011-09-30T21:57:52.693 に答える
0

C# で Convert 関数を使用しました。私が変換を行っている方法は、リフレクションを使用しています。:

Type type = this.myObject.GetType();

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

これはすべて、変換したい型がわかっていることを前提としています。スイッチを作成して、反映したい複数のタイプを持つこともできます。

于 2016-07-21T17:27:44.847 に答える
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);
}
于 2011-09-30T21:23:27.880 に答える