gpt4 book ai didi

c# - 如何从 PowerShell 调用 C# 方法,其签名具有标记为 'params' 的参数

转载 作者:太空宇宙 更新时间:2023-11-03 14:50:52 26 4
gpt4 key购买 nike

我正在尝试从具有以下签名的 PowerShell 调用 C# 库方法:

public void Load<T>(T thing, params Expression<Func<T, object>>[] retrievals);

对于“检索”参数,我只想传递一个表达式参数,但当我这样做时,PowerShell 会给我以下错误:

Cannot find an overload for "Load" and the argument count: "2".

我正在尝试使用这个:

$context.Load($thing, @($expressionTree1))

它一直抛出那个错误。

我使用的是 PowerShell 5,C# 库是 SharePoint 2016 的客户端对象模型。

有什么想法吗?

最佳答案

在您的情况下,它应该是最短的解决方案。

$code = 
@'
using System;
using System.Linq.Expressions;

public class Entity
{
public string Property1 { get; set; }
public int Property2 { get; set; }
}

public class TestClass
{
public void Load<T>(T thing, params Expression<Func<T, object>>[] retrievals)
{
foreach (var retrieval in retrievals)
{
System.Console.WriteLine("Retrieval: " + retrieval);
}
}

private static Expression<Func<T, object>> FuncToExpression<T>(Func<T, object> f)
{
return x => f(x);
}

public void Load2<T>(T thing, params Func<T, object>[] retrievals)
{
var funcs = new Expression<Func<T, object>>[retrievals.Length];

for (int i = 0; i < retrievals.Length; i++)
{
funcs[i] = FuncToExpression(retrievals[i]);
}

this.Load<T>(thing, funcs);
}

public void Test1()
{
Entity entity = new Entity();
this.Load<Entity>(entity, e => e.Property1, e => e.Property2);
}
}
'@

有辅助方法 Load2 但您可以轻松地将其重写为 PowerShell。关键是另一个辅助方法 FuncToExpression。可以“手动”编译 Linq 表达式,但要复杂得多。

使用示例:

    Add-Type -TypeDefinition $code -Language CSharp
$o = New-Object TestClass
$o.Test1()
$entity = New-Object Entity
$func1 = [Func`2[Entity, object]]{ param($e) $e.Property1 }
$func2 = [Func`2[Entity, object]]{ param($e) $e.Property2 }
$o.Load2($entity, [Func`2[Entity, object][]]@($func, $func2))

关于c# - 如何从 PowerShell 调用 C# 方法,其签名具有标记为 'params' 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51835915/

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