使用表达式<func>从Powershell中调用参数调用C#方法

时间:2017-08-03 15:43:54

标签: c# powershell lambda

我有以下示例C#类:

Class1.Method1(() => "Hello World");

要从C#调用它,就像这样简单:

Add-Type -Path "ClassLibrary1.dll"
$func = [Func[string]] { return "Hello World" }
$exp = [System.Linq.Expressions.Expression]::Call($func.Method);
[ClassLibrary1.Class1]::Method1($exp)

我不能为我的生活弄清楚如何从Powershell中调用它。我的最后一次尝试是:

Exception calling "Call" with "1" argument(s): "Incorrect number of arguments supplied for call to method 'System.String lambda_method(System.Runtime.CompilerServices.Closure)'"
At C:\Users\Mark\Documents\Visual Studio 2015\Projects\ClassLibrary1\ClassLibrary1\test.ps1:4 char:1
+ $exp = [System.Linq.Expressions.Expression]::Call($func.Method);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentException
+ $exp = [System.Linq.Expressions.Expression]::Call($func.Method);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentException

但这会导致错误:

$func

我相信我的sort不正确;任何想法?

1 个答案:

答案 0 :(得分:2)

好的,想通了(感谢@DavidG的链接)。关键是首先在C#中写出System.Linq.Expressions.Expression树。然后,转换为Powershell之后很容易:

所以,在C#中:

Class1.Method1(() => "Hello World");

类似于:

var exp = Expression.Constant("Hello World", typeof(string));
var lamb = Expression.Lambda<Func<string>>(exp);
Class1.Method1(lamb);

在Powershell中:

$exp = [System.Linq.Expressions.Expression]::Constant("Hello World", [string]);
$lamb = [System.Linq.Expressions.Expression]::Lambda([Func[string]], $exp);
[ClassLibrary1.Class1]::Method1($lamb);