在c# . net中动态地转换为类型

本文关键字:转换 类型 动态 net | 更新日期: 2023-09-27 18:10:05

备选标题:在运行时动态转换为类型

我想将Object转换为将在运行时分配的类型。

例如,假设我有一个函数,它将一个字符串值(从TextBox or Dropdownlist)分配给Object.Property

如何将值转换为合适的类型?例如,它可以是整数、字符串或enum。

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);
}

在c# . net中动态地转换为类型

您需要使用Convert.ChangeType(…)函数[注意:在下面的函数中,输入propertyValue可以很容易地具有object类型…]我刚刚有一个字符串版本预烤]:

/// <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);
}

通用类型转换器是你所寻求的!?这可不是一件容易的事。

试试这个方法:

通用型转换器

你可以在NuGet Install-Package UniversalTypeConverter

此外,在这里使用Generics是不可能的吗?如果您至少知道转换的目标类型,将有助于解决这个问题。

这里有另一种方法,但我不确定

不支持泛型类型:
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);
} 

我不确定它是否有效,但请尝试一下:

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);
}

我使用了c#中的Convert函数。我做转换的方式是使用反射。:

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

这些都是假设你知道你想要转换成什么类型。你甚至可以做一个切换,设置多个你想要反映的类型。