如何将对象转换为在运行时提取的Type [英] How to cast an object to a Type extracted at runtime
问题描述
我在运行时使用反射来获取对象的类型,或者为此问题而具有实例属性类型的对象,然后我需要将现有变量的类型更改为该新发现的类型.这可能吗?例如,以下代码在所指示的行中不不起作用:
I am using reflection to get an object's type, or for this issue an object that has instance properties type, at runtime and then I need to change an existing variable's type into that newly found type. Is this possible? For example, the following code does not work in the line indicated within:
Public Sub DoSomething(x As T, y As T, exp As String)
'This is a instance property on the object of a different type
'i.e. '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可用,并且思想我开始研究.下面的代码行实际上可以编译,但是在运行时会在下面给出以下错误.
I also tried CTypeDynamic avialable in .NET 4.0 and thought I was on to something. The line of code below actually compiles but at runtime gives the following error below.
x = CTypeDynamic(x, tp.GetType())
从类型"[TypeOfT]"到类型"RuntimeType"的转换无效.
Conversion from type '[TypeOfT]' to type 'RuntimeType' is not valid.
请注意,[TypeOfT]实际上不在错误消息中,而是传递给方法的对象类型.
Note above, [TypeOfT] is not actually in the error message but the type of object passed into the method.
那么,是否仍然没有Case语句或一堆'If TypeOf(...')语句,我可以使用在运行时找到的类型并将其动态转换为另一个对象?
So is there anyway without Case Statements or a bunch of 'If TypeOf(...' statements that I can use the type I found at runtime and convert another object to its type dynamically?
谢谢!(解决方案可以在VB.NET或C#中-谢谢)
推荐答案
尝试
这篇关于如何将对象转换为在运行时提取的Type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!