1

Given a C# function as below, what is the valid syntax in IronPython to call it?

public void MyFunction( Expression<Action> foo)
{

}
Joe
  • 631
  • 2
  • 7
  • 18

1 Answers1

0

You just need to construct an expression that fits the pattern. In the expression library, a generic expression is a specialized lambda expression. So you would just write the appropriate lambda expression in IronPython. Unfortunately you won't get any compiler help with this as you would in C#, you'll have to build it by hand.

Fortunately, the dlr will be very forgiving and will infer some types for you where possible.

Given a library SomeLibrary.dll, with a given class:

using System;
using System.Linq.Expressions;

namespace SomeNamespace
{
    public class SomeClass
    {
        public void SomeMethod(Expression<Action> expr) => Console.WriteLine(expr);
    }
}
import clr

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

from System import Console, Array, Type, Action
from System.Linq.Expressions import *
from SomeNamespace import SomeClass

# build the expression
expr = Expression.Lambda(
    Expression.Call(
        clr.GetClrType(Console).GetMethod('WriteLine', Array[Type]([str])),
        Expression.Constant('Hello World')
    )
)

# technically, the type of expr is Expression as far as C# is concerned
# but it happens to be an instance of Expression<Action> which the dlr will make work
SomeClass().SomeMethod(expr)
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • thanks, that really helped. How would you pass non-static method (Console.Writeline in this example is static)? – Joe Oct 25 '16 at 14:02
  • You won't be able to pass that in directly, it's not an expression and can't be converted to one. You can build an expression that just calls it. It's the same as the example I've shown here, but without the parameters. – Jeff Mercado Oct 25 '16 at 14:58