简体   繁体   English

如何使用CPython使泛型在Python.NET中工作

[英]How can I get generics to work in Python.NET with CPython

How can I get generics to work in Python.NET with CPython. 如何使用CPython在Python.NET中使用泛型。 I get an error when using the subscript syntax from Python.NET Using Generics Python.NET使用泛型使用下标语法时出现错误

TypeError: unsubscriptable object

With Python 2.7.11 + pythonnet==2.1.0.dev1 使用Python 2.7.11 + pythonnet == 2.1.0.dev1

>python.exe
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> from System import EventHandler
>>> from System import EventArgs
>>> EventHandler[EventArgs]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsubscriptable object

I've also tried pythonnet==2.0.0 and building form github ca15fe8 with ReleaseWin x86 and got the same error. 我也尝试了pythonnet == 2.0.0并使用ReleaseWin x86构建github ca15fe8并出现了相同的错误。

With IronPython-2.7.5: 使用IronPython-2.7.5:

>ipy.exe
IronPython 2.7.5 (2.7.5.0) on .NET 4.0.30319.0 (32-bit)
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> from System import EventHandler
>>> from System import EventArgs
>>> EventHandler[EventArgs]
<type 'EventHandler[EventArgs]'>

You can get the generic class object explicitly: 您可以显式获取通用类对象:

EventHandler = getattr(System, 'EventHandler`1')

The number indicates the number of generic arguments. 该数字表示通用参数的数量。

That doesn't work because there are both generic and non-generic versions of the EventHandler class that exist in the System namespace. 这是行不通的,因为System命名空间中同时存在EventHandler类的通用版本和非通用版本。 The name is overloaded. 名称超载。 You need to indicate that you want the generic version. 您需要指出您想要通用版本。

I'm not sure how exactly Python.NET handles overloaded classes/functions but it seems like it has an Overloads property. 我不确定Python.NET如何精确处理重载的类/函数,但似乎它具有Overloads属性。 Try something like this and see how that goes: 尝试这样的事情,看看效果如何:

 
 
 
 
  
  
  EventHandler_EventArgs = EventHandler.Overloads[EventArgs]
 
 
  

(this doesn't work) (这不起作用)

It doesn't seem like Python.NET has ways to resolve the overloaded class name, each overload is treated as separate distinct types (using their clr names). 看起来Python.NET似乎没有办法解析重载的类名,每个重载都被视为单独的不同类型(使用其clr名称)。 It doesn't do the same thing as IronPython and lump them into a single containing type. 它与IronPython做不同的事情,并将它们组合为一个包含类型。

In this particular case, the EventArgs name corresponds to the non-generic EventArgs type. 在这种特殊情况下, EventArgs名称对应于非通用EventArgs类型。 You'll need to get the appropriate type directly from the System module as filmor illustrates. 如filmor所示,您需要直接从“系统”模块中获取适当的类型。

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

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