简体   繁体   English

如何将对象强制转换为在运行时提取的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

I also tried CTypeDynamic avialable in .NET 4.0 and thought I was on to something. 我也尝试过.NET 4.0中的CTypeDynamic avialable,并认为我正在做些什么。 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. 从类型'[TypeOfT]'到类型'RuntimeType'的转换无效。

Note above, [TypeOfT] is not actually in the error message but the type of object passed into the method. 请注意,[TypeOfT]实际上并不在错误消息中,而是传递给方法的对象类型。

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? 那么无论如何没有Case语句或一堆'If TypeOf(...'语句,我可以使用我在运行时找到的类型并动态地将另一个对象转换为它的类型?

Thanks! 谢谢! ( solution can be in VB.NET or C# - thank you) 解决方案可以在VB.NET或C#中 - 谢谢)

Try Convert.ChangeType 尝试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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM