使用<Func>来自 Powershell 的表达式参数调用 C# 方法



我有以下示例 C# 类:

public static class Class1
{
public static string Method1(Expression<Func<string>> efs)
{
return efs.Compile().Invoke();
}
}

要从 C# 调用它,它就像:

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

我一辈子都想不出如何从Powershell中调用它。 我的最后一次尝试是:

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

但这会导致错误:

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:UsersMarkDocumentsVisual Studio 2015ProjectsClassLibrary1ClassLibrary1test.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不正确;有什么想法吗?

好的,想通了(感谢@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);

最新更新