我使用反射来获取对象的类型,或者对于此问题,在运行时使用具有实例属性类型的对象,然后我需要将现有变量的类型更改为新找到的类型。这可能吗?例如,以下代码 not 在
中指示的行中工作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 avialable和思想我正在做些什么。下面的代码行实际编译但在运行时会在下面给出以下错误。
x = CTypeDynamic(x, tp.GetType())
从“[TypeOfT]”类型转换为“RuntimeType”类型无效。
上面注意,[TypeOfT]实际上并不在错误消息中,而是传递给方法的对象类型。
无论如何没有Case语句或一堆'If TypeOf(...'语句,我可以使用我在运行时找到的类型并将另一个对象动态转换为它的类型?
谢谢! (解决方案可以在VB.NET或C# - 谢谢)
答案 0 :(得分:7)
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