c#在运行时创建(或强制转换)特定类型的对象

本文关键字:类型 对象 转换 运行时 创建 | 更新日期: 2023-09-27 18:12:45

我需要在运行时创建特定类型的对象(或强制转换该特定类型)。

我有一个程序,它有一个包含属性名和对象的字典。

Dictionary<string, Type> attributes = new Dictionary<string, Type>();

这个字典是外部输入的(在运行时)

的例子:

attributes.Add("attrName1", typeof(string));
attributes.Add("attrName2", typeof(long));
attributes.Add("attrName3", typeof(DateTime));
attributes.Add("attrName4", typeof(ArrayList));

程序需要从源中检索数据(属性值),并以特定类型返回。

,

The value of an attribute called "attrName1" needs to be returned as an object of type "string"
The value of an attribute called "attrName2" needs to be returned as an object of type "long"
The value of an attribute called "attrName3" needs to be returned as an object of type "DateTime"
...

我写了一个函数返回一个属性作为一个对象

public object GetTheValue(string AttribName)
{
  object oReturn;
  // do whatever to retreive the value of the attribute called <AttribName> and put it in oReturn
  return oReturn;
}

对于每个属性调用这个函数来检索它的值

object Buffer;
object Val;
foreach(KeyValuePair<string, Type> Attribute in attributes)
{
    Buffer = GetTheValue(Attribute.Key);
    //Here i need to cast/convert the "Buffer object to the typeof Attribute.Value
    // Stuff I tried but doesn't work :( 
    // (Attribute.Value.GetType())Buffer;
    // (typeof(Attribute.Value))Val
    // Buffer as (Attribute.Value.GetType())
    // Buffer as (typeof(Attribute.Value))
    // Val = new (typeof(Attribute.Value))(Buffer)
}

目前我看到的唯一选项是使用switch语句遍历所有可能的类型,并将返回的对象强制转换为该类型。

有人有其他选择或解决方案吗?

c#在运行时创建(或强制转换)特定类型的对象

为什么不使用如下格式:

Val = Convert.ChangeType(Buffer, typeof(Attribute.Value));

ChangeType仅适用于实现了IConvertable接口的类型

仅适用于实现IConvertible接口的类型:

要使转换成功,value必须实现IConvertible接口,因为该方法只是将调用包装到适当的IConvertible方法。该方法要求将值转换为conversionType支持

尝试使用表达式,例如:

Dictionary<string, Type> attributes = new Dictionary<string, Type>();
attributes.Add("attrName1", typeof(string));
attributes.Add("attrName2", typeof(long));
attributes.Add("attrName3", typeof(DateTime));
attributes.Add("attrName4", typeof(ArrayList));
object[] Items = new object[4];
Items[0] = "Test";
Items[1] = 11111L; 
Items[2] = new DateTime();
Items[3] = new ArrayList();
object Buffer;
object Val;
int i = 0;
foreach(KeyValuePair<string, Type> attr in attributes)
{
    Buffer = Items[i++];
    //Try this expression 
    var DataParam = Expression.Parameter(typeof(object), "Buffer");
        var Body = Expression.Block(Expression.Convert(Expression.Convert(DataParam, attr.Value), attr.Value));
        var Run = Expression.Lambda(Body, DataParam).Compile();
        var ret = Run.DynamicInvoke(Buffer);

}