我正在使用反射来获取对象的类型,或者对于这个问题,在运行时获取具有实例属性类型的对象,然后我需要将现有变量的类型更改为新发现的类型。这可能吗?例如,以下代码不在以下指示的行中工作:
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# 中 - 谢谢)
最佳答案
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
关于c# - 如何将对象转换为在运行时提取的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9009986/