简体   繁体   English

如何将PowerShell函数传递给采用Func的.NET方法 <T1, T2> ?

[英]How can I pass a PowerShell function to a .NET method that takes a Func<T1, T2>?

I need to create a .NET object in PowerShell. 我需要在PowerShell中创建一个.NET对象。 The signature for the constructor is: 构造函数的签名是:

public ObjCTor(TClient param1, Func<TClient, IInterface> param2)

and the class is defined as: 并且该类定义为:

public class ObjCTor<TClient> : IOtherInt1, IOtherInt2 where TClient : ConcreteBase

The first parameter is easy enough. 第一个参数很简单。 I'm stumped on the second. 我被困在第二个。 How can I pass a PowerShell function as Func<T1, T2> ? 如何将PowerShell函数作为Func<T1, T2>传递?

UPDATED 更新

The syntax supplied by Jason wasn't quiet correct. Jason提供的语法并不安静。 This works: 这有效:

$= New-Object "ObjCTor[TClient]" -ArgumentList $param1,$functionToCall

I was also missing the $args[0] as a parameter in my scriptblock/delegate. 我也错过了$args[0]作为我的scriptblock / delegate中的参数。 This is what I should've had: 这就是我应该拥有的:

$functionToCall = { Get-Blah $args[0] }

PowerShell can convert a ScriptBlock to a delegate, so something like this might work fine: PowerShell可以将ScriptBlock转换为委托,所以像这样的东西可能正常工作:

$sb = { param($t1) $t1 }
New-Object "ObjCTor[CClient, Func[CClient,IInterface]]" -ArgumentList $param1,$sb

Note that PowerShell cannot deduce generic type arguments from a ScriptBlock. 请注意,PowerShell无法从ScriptBlock中推断出泛型类型参数。 In your case, ObjCTor looks like a generic class so type deduction isn't a factor, but if you were calling a generic method, things could get messy. 在你的情况下,ObjCTor看起来像一个泛型类,所以类型推导不是一个因素,但如果你调用泛型方法,事情可能会变得混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM