How to pass IronPython instance method for function parameter (C #) of type `Func <Foo>`

I am trying to assign an IronPython instance method to a C # parameter Func<Foo>.

In C #, I will have a method like:

public class CSharpClass
{
    public void DoSomething(Func<Foo> something)
    {
        var foo = something()
    }
}

And call it from IronPython as follows:

class IronPythonClass:
    def foobar(self):
        return Foo()
CSharpClass().DoSomething(foobar)

But I get the following error:

TypeError: expected Func [Foo], received method instance

+3
source share
2 answers

OK I think I could find a solution:

import clr
clr.AddReference('System')
clr.AddReference('System.Core')

from System import Func

class IronPythonClass:
def foobar(self):
    return Foo()

CSharpClass().DoSomething(Func[Foo](foobar))

An interesting bit is the constructor Func[Foo]:)

+2
source

The first option is to use the static method. For this you need to use a decorator @staticmethod:

class IronPythonClass: 
    @staticmethod
    def foobar(): 
         return Foo() 

CSharpClass().DoSomething(IronPythonClass.foobar)

, , :

class IronPythonClass: 
    def foobar(self): 
         return Foo() 

ipc = IronPythonClass()
CSharpClass().DoSomething(ipc.foobar) # using ipc.foobar binds 'ipc' to the 'self' parameter

, Func<object, Foo> , .

+1

Source: https://habr.com/ru/post/1740939/


All Articles