c# - 如何将对象转换为在运行时提取的类型

标签 c# .net vb.net 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
'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# 中 - 谢谢)

最佳答案

尝试 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

关于c# - 如何将对象转换为在运行时提取的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9009986/

相关文章:

c# - 检查名称属性中是否存在值

java - 此 C# 泛型方法模式的等效 Java 实现是什么

.net - Azure:无法执行请求的操作,因为 VM 大小不支持存储帐户类型 'Premium_LRS'

.net - 在发布构建期间将依赖项移至另一个文件夹

asp.net - 预期表达

c# - 长后台进程刷新 ui wpf

c# - COM异常 : 80040154

c# - process.MainWindowHandle 为零?

c# - 登录按钮样式属性

c# - 如何获取电话号码