什么是“<调用>d__40”?

Chr*_*ter 3 c# powershell powershell-cmdlet

使用 Powershell,System.Management.Automation.Cmdlet.Invoke() 返回类型的对象'<Invoke>d__40'而不是指定的 OutputType。

重现:

  1. SendGreeting 示例 cmdlet复制到 .\ExampleCmdlet.cs
  2. powershell -NoProfile
  3. Add-Type -Path .\ExampleCmdlet.cs
  4. $command = [SendGreeting.SendGreetingCommand]::new()
  5. $command.Name = 'Person'
  6. $invoke = $command.Invoke()
  7. $invoke.GetType()

预期[string]
实际[<Invoke>d__40]

$PS版本表:

Name                           Value
----                           -----
PSVersion                      5.1.19041.1237
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.1237
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
Run Code Online (Sandbox Code Playgroud)

Get-Member -InputObject $invoke揭示这个来实现IEnumerator和一些玩弄.MoveNext().Current有时会输出预期的"Hello Person!"结果。

这是什么<Invoke>d__40类型?
为什么$command.Invoke()不直接返回预期的字符串输出?

Gur*_*ron 5

<Invoke>d__40是编译器生成的类的名称:

Cmdlet.Invoke/Cmdlet.Invoke<T>返回IEnumerable/IEnumerable<T>并使用它实现yield return,这会导致编译器生成特殊的命名类(编译器可以在标识符中使用<>符号,而开发人员不能),它实现IEnumerable/ IEnumerable<T>(例如,查看反编译)。