Assigning an IronPython method to a C# delegate

2019-01-25 17:29发布

I have a C# class that looks a little like:

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 */
}

And I have an IronPython script that gets run in the application that looks like

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

But when ProcessMethod gets called (outside of IronPython), after this assignment, the default method is run.

I know the script is run because other parts of the script work.

How should I be doing this?

1条回答
太酷不给撩
2楼-- · 2019-01-25 18:14

I did some further Googling and found a page about the darker corners of IronPython: http://www.voidspace.org.uk/ironpython/dark-corners.shtml

What I should be doing is this:

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)
查看更多
登录 后发表回答