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

时间:2015-09-14 17:04:30

标签: c#

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

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

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语句遍历所有可能的Types并将返回的对象强制转换为该Type。

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

2 个答案:

答案 0 :(得分:0)

为什么不使用类似的东西:

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

答案 1 :(得分:0)

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

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

  

要使转换成功,值必须实现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);


}