Powershell 如何创建委托
问题描述:
我不熟悉powershell.我正在尝试在 C# 中做一些单行代码的事情,但在 powershell 中它很痛苦:(
I am not to familar with powershell. I am trying to do something that would be a single line of code in C# but in powershell it is a pain :(
在下面的三行中 wow3 抛出了一个错误.任何人都知道为什么 wow3 会抛出未找到类型的错误?委托的这种语法仅适用于内置类型吗?
In the three lines below wow3 throws an error. Anyone know why wow3 throw a type not found error? Does this syntax for delegates only work for built in types?
$wow1 =[System.Action[int]]
$wow2 =[MyType]
$wow3 =[System.Action[MyType]]
答
PowerShell 这一行:
This line of PowerShell:
$wow1 = [System.Action[int]]
等于这行C#:
var d = typeof(System.Action<int>);
也就是说,$wow1
包含一个 System.RuntimeType
.这真的是你想要做的吗?
That is, $wow1
contains a System.RuntimeType
. Is that really what you are trying to do?
也许你想要这样的东西?
Perhaps you want something like this instead?
C:\PS> [Action[int]]$action = {param($i) Write-Host "i is $i"}
C:\PS> $action.Invoke(10)
i is 10