can you typecast a .NET object in IronPython?

喜夏-厌秋 提交于 2019-11-30 05:17:23

问题


I'm interfacing with a .NET API in IronPython. The API is returning an object of the wrong type (some kind of generic object). I suspect that the problem is not showing up in their C# code because the type declaration when the object is constructed is forcing the returned object to the correct type. Is it possible to typecast an .NET object in IronPython? I think this would do the trick.


回答1:


To force a conversion you can do:

import clr
convertedObject = clr.Convert(someObject, someType)

This will search for and run implicit/explicit conversions if one exists.

Note: available since IronPython 2.6.




回答2:


If you need to cast numeric value to an enum use the following, because the code above does not work for enums, but only for reference types:

Enum.ToObject(CustomEnumType, value)



回答3:


clr.Convert doesnt exist in IronPython 2.0 . This is not a solution to typecast a .NET object in IronPython?, but it's a workaround to convert the data if you really need it to use it from IronPython

Create a class like this in VB.NET and compile it into a DLL

Imports Microsoft.VisualBasic

    Public Class MyConvert

        Shared Function converttype(ByVal value As String) As Integer
            Return CInt(value)
        End Function

    End Class

Then in IronPython you do

clr.AddReference('MyConvert')
from MyConvert import converttype         
converted_value = converttype("2.0")



回答4:


I had a similar problem on a project a few months ago. This was my fix:

import clr

clr.GetPythonType(x)

x can be a .NET type or a type that is in a dll file that you have imported using clr.

I am not a C# programmer, but I have been told by C# programmer colleagues that this code in C# would be:

typeof(x)

Hope this helps



来源:https://stackoverflow.com/questions/1439457/can-you-typecast-a-net-object-in-ironpython

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