6

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?

Matt Ellen
  • 11,268
  • 4
  • 68
  • 90

1 Answers1

12

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)
Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
  • Replying to an old post, but wouldn't you also need to import the name IDataSource from somewhere for this to work? – B. Fuller Dec 07 '17 at 01:33
  • yeah, would have been great if you could have explained a little what the above code does, especially the last line. – not2qubit Nov 19 '20 at 20:37
  • 1
    @not2qubit the last line is assigning the `Func` that holds the function `OtherMethod`, defined in the above python, to the property `ProcessMethod`, which is defined in the question. The important lines, I suppose, are the two extra imports, and the call to `clr.AddReference`, that allow me to use `Func` – Matt Ellen Nov 19 '20 at 21:02