将IronPython方法分配给C#委托

6

我有一个 C# 类,看起来有点像:

public class MyClass
{
    private Func<IDataCource, object> processMethod = (ds) =>
                                                          {
                                                            //default method for the class
                                                          }

    public Func<IDataCource, object> ProcessMethod
    {
        get{ return processMethod; }
        set{ processMethod = value; }
    }

    /* Other details elided */
}

我有一个 IronPython 脚本,用于在应用程序中运行,看起来像这样:

from MyApp import myObj #instance of MyClass

def OtherMethod(ds):
    if ds.Data.Length > 0 :
        quot = sum(ds.Data.Real)/sum(ds.Data.Imag)
        return quot
    return 0.0

myObj.ProcessMethod = OtherMethod

但是当ProcessMethod被调用时(在IronPython之外),在此赋值之后,将运行默认方法。
我知道脚本正在运行,因为脚本的其他部分也在工作。
我该如何做?
1个回答

12

我继续谷歌搜索并找到了一篇关于IronPython一些黑暗角落的页面:http://www.voidspace.org.uk/ironpython/dark-corners.shtml

我应该这样做:

from MyApp import myObj #instance of MyClass
import clr
clr.AddReference('System.Core')
from System import Func

def OtherMethod(ds):
    if ds.Data.Length > 0 :
        quot = sum(ds.Data.Real)/sum(ds.Data.Imag)
        return quot
    return 0.0

myObj.ProcessMethod = Func[IDataSource, object](OtherMethod)

回复一篇旧帖子,但是为了让这个工作正常运行,您也需要从某个地方导入IDataSource的名称吗? - B. Fuller
是的,如果您能稍微解释一下上面的代码,特别是最后一行,那就太好了。 - not2qubit
1
@not2qubit 最后一行是将包含上述 Python 中定义的 OtherMethod 函数的 Func<T1, T2> 赋给了问题中定义的 ProcessMethod 属性。我认为重要的是两个额外的导入行和对 clr.AddReference 的调用,这使我能够使用 Func<T1, T2> - Matt Ellen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接