给定C#函数如下,IronPython中调用它的有效语法是什么?
public void MyFunction( Expression<Action> foo)
{
}
答案 0 :(得分:0)
您只需要构建一个适合该模式的表达式。在表达式库中,泛型表达式是一种专用的lambda表达式。所以你只需要在IronPython中编写适当的lambda表达式。遗憾的是,您不会像在C#中那样获得任何编译器帮助,您必须手动构建它。
幸运的是,dlr将非常宽容,并会在可能的情况下为您推断出某些类型。
给定一个库SomeLibrary.dll
,给定一个类:
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)