How to cast an object to a Type extracted at runtime

不想你离开。 提交于 2020-01-12 07:27:09

问题


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

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())

Conversion from type '[TypeOfT]' to type 'RuntimeType' is not valid.

Note above, [TypeOfT] is not actually in the error message but the type of object passed into the method.

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?

Thanks! (solution can be in VB.NET or C# - thank you)


回答1:


Try 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


来源:https://stackoverflow.com/questions/9009986/how-to-cast-an-object-to-a-type-extracted-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!