gpt4 book ai didi

powershell - 构造方法调用

转载 作者:行者123 更新时间:2023-12-02 23:13:17 25 4
gpt4 key购买 nike

尝试遵循本指南:https://github.com/Readify/Neo4jClient/wiki/cypher-examples#get-all-users-by-label
我需要创建一个lambda表达式,以便将其提供给Return方法。在C#中,它看起来像这样:

.Return(n => n.As<Project>())

在Powershell中,我采用了这种方式(按照@PetSerAl的建议: Return overload fails):
$exp = [System.Linq.Expressions.Expression]
$param = $exp::Parameter([Neo4jClient.Cyper.ICypherResultItem], "n")
$body = $exp::TypeAs($p, (new-object Project).GetType())
$lambda = $exp::Lambda([Func[Project]], $body, $p)

这样,传递给lambda表达式的参数将被键入以接收Neo4j表达式将传递的内容,并且该方法的主体将其转换为 Project(本地定义的类)。现在我可以将其传递给我的方法:
$something.Return($lambda)

但是,我得到这个错误

Exception calling "Return" with "1" argument(s): "The expression must be constructed as either an object initializer (for example: n => new MyResultType { Foo = n.Bar }), an anonymous type initializer (for example: n => new { Foo = n.Bar }), a method call (for example: n => n.Count()), or a member accessor (for example: n => n.As().Bar). You cannot supply blocks of code (for example: n => { var a = n + 1; return a; }) or use constructors with arguments (for example: n => new Foo(n)). If you're in F#, tuples are also supported. Parameter name: expression" At line:1 char:1 + $neo.Cypher.Match("n").Return($return) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ArgumentException



这清楚表明我没有正确制定lambda表达式的主体。谁能建议应该怎么做?

最佳答案

C#中,您有:

.Return(n => n.As<Project>())

如果我们将其取出并查看类型, n => n.As<Project>()为:
Expression<Func<ICypherResultItem, Project>>

为了在 Expression Trees中使用 C#来创建该代码,我们最终要做类似的事情:
ParameterExpression parameter = Expression.Parameter(typeof (ICypherResultItem), "n");
MethodCallExpression right = Expression.Call(parameter, typeof (ICypherResultItem).GetMethod("As").MakeGenericMethod(typeof(Project)));
Expression<Func<ICypherResultItem, Project>> expression = Expression.Lambda<Func<ICypherResultItem, Project>>(right, parameter);

因此,将其转换为PowerShell,我认为它类似于:
$exp = [System.Linq.Expressions.Expression]
$param = $exp::Parameter([Neo4jClient.Cypher.ICypherResultItem], "n")
$body = $exp::Call($param, [Neo4jClient.Cypher.ICypherResultItem].GetMethod("As").MakeGenericMethod[Project])
$lambda = $exp::Lambda([Func[ICypherResultItem, Project]], $body, $param)

我不是,而是一个强力的人,我怀疑您将能够更好地翻译 C#,但希望这能使您走上正确的路...

*更新I *
一个小巧的解决方案,使其可以正常工作。声明一个变量以保存 MakeGenericMethod期望的类型数组,并将其传递给:
$PrjType = @((new-object Project).GetType())
$body = $exp::Call($param, [Neo4jClient.Cypher.ICypherResultItem].GetMethod("As").MakeGenericMethod($PrjType))

关于powershell - 构造方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30514603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com