代码之家  ›  专栏  ›  技术社区  ›  Mark

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

  •  2
  • Mark  · 技术社区  · 9 年前

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

    从C#中调用它非常简单:

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

    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:\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 不正确;有什么想法吗?

    1 回复  |  直到 9 年前
        1
  •  3
  •   Mark    9 年前

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

    因此,在C#中:

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

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

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