如何将对象强制转换为在运行时提取的Type

我使用reflection来获取对象的类型,或者对于此问题,在运行时使用具有实例属性类型的对象,然后我需要将现有变量的类型更改为新找到的类型。 这可能吗? 例如,以下代码在以下行中指示的行中不起作用:

Public Sub DoSomething(x As T, y As T, exp As String) 'This is a instance property on the object of a different type 'ie 'T.AnotherType' We need to reflect to find out what type of object 'AnotherType is and work with it If exp.Split(".").Count Then Dim tp As Type = Nothing tp = x.GetType tp = tp.GetProperty(exp.Split(".").ElementAt(0)).PropertyType() 'Line below works, gets the right type, and now I need both x and y values passed in to be cast to this type. Dim typ As Type = tp.GetType 'The line below WILL NOT work; can't cast to an unknown type at compile time - makes sense, but this is where I need a solution x = DirectCast(x, typ) End If End Sub 

我也尝试过.NET 4.0中的CTypeDynamic avialable,并认为我正在做些什么。 下面的代码行实际编译但在运行时给出以下错误。

 x = CTypeDynamic(x, tp.GetType()) 

从类型'[TypeOfT]’到类型’RuntimeType’的转换无效。

请注意,[TypeOfT]实际上并不在错误消息中,而是传递给方法的对象类型。

那么无论如何没有Case语句或一堆’If TypeOf(…’语句,我可以使用我在运行时找到的类型并动态地将另一个对象转换为它的类型?

谢谢! ( 解决方案可以在VB.NET或C#中 – 谢谢)

尝试Convert.ChangeType

 If exp.Split(".").Count Then Dim tp As Type = Nothing tp = x.GetType tp = tp.GetProperty(exp.Split(".").ElementAt(0)).PropertyType() 'Line below works, gets the right type, and now I need both x and y values passed in to be cast to this type. Dim typ As Type = tp.GetType x = Convert.ChangeType(x, typ) End If