python3 pythonnet 泛型委托

python3 pythonnet generic delegates

我在 windows7 上安装了 64 位 CPython 3.4。我使用 pythonnet 包 (2.0.0.dev1)。 我想实例化动作委托,但它给我一个错误。

def display(num):
     print("num=", num)

import clr
clr.AddReference("System")
import System

paction=System.Action[System.Int32](display)

我收到这个错误:

TypeError Traceback (most recent call last) in () ----> 1 paction=System.Action[System.Int32](display) TypeError: unsubscriptable object

我想这就是指定泛型的方式。

我检查了文档和this post,仍然没有看到问题。 我也尝试了一下 Overload 方法,但也没有帮助:

paction=System.Action.Overloads[System.Int32](display)

TypeError Traceback (most recent call last) in () ----> 1 paction=System.Action.Overloads[System.Int32](display) TypeError: No match found for constructor signature

我也遇到了这个问题。我创建了一个变通方法以在 Python.Net

中使用 Actions

使用以下代码创建 .net class 库项目:

using System;

namespace PythonHelper
{
    public class Generics
    {

        public static Action<T1, T2> GetAction<T1, T2>(Func<T1, T2, object> method)
        {
            return (a, b) => method(a,b);
        }

    }
}

将其编译为 dll 文件并将其包含在您的 Python.net 项目中 (clr.AddReference('PythonHelper'))

现在,在您的 Python.net 项目中,您可以使用以下代码创建泛型:

import clr
clr.AddReference('PythonHelper')
import System
from System import DateTime, Func
from PythonHelper import Generics

def myCallback(a,b):
    print a, b

func = Func[DateTime, DateTime, System.Object](myCallback)
action = Generics.GetAction[DateTime, DateTime](func)

如果您需要创建带有更多或更少参数的动作,您必须自己添加另一个 GetAction 方法。

问题是 System.Action(没有参数,因此不是泛型)正在隐藏 System.Action<T>,而 System.Func 直接映射到 System.Func<T>。我想这是因为 System.Func 总是 有一个泛型参数,而且似乎有一个针对泛型的重载实现。

Python.NET 中泛型的名称是 Action`1(通常:Action`NN 是泛型参数的数量)。您可以通过在模块上使用 getattr 来获取包装器对象:

Action = getattr(System, "Action`1")
action = Action[Int32](display)