【问题标题】:Reference .NET Generic Nested Type in Powershell Core参考 Powershell Core 中的 .NET 通用嵌套类型
【发布时间】:2021-07-19 23:45:23
【问题描述】:

正如标题所示,我试图在 Powershell Core 中引用嵌套通用类型。

我发现使用 + 符号而不是 . 来访问 Powershell 中的嵌套类型...但语法似乎不适用于“嵌套通用类型”...编译器没有'不喜欢代码语法错误。

Special use of plus (+) sign in Powershell

有没有人成功地让它工作,或者这是一个已知的限制?

[System.Collections.Generic.Dictionary[[string], [int]]+Enumerator] GetEnumerator()

【问题讨论】:

  • 看起来语法可能是[System.Collections.Generic.Dictionary`2+Enumerator[[String],[Int32]]]::new(),但它不起作用。 InvalidOperation: An error occurred while enumerating through a collection: Object reference not set to an instance of an object..(我通过新建字典、获取枚举器并检查它的类型信息发现了这一点。)
  • 谢谢...实际上对我有用...我能够使用该语法定义适当的方法签名。我没有调用::new(),而是在底层字典实现上调用.GetEnumerator()

标签: powershell powershell-core


【解决方案1】:

Daniel提供了解决方案:

[System.Collections.Generic.Dictionary`2+Enumerator[string, int]]

返回感兴趣的类型(注意嵌套在各个泛型类型参数stringint 周围的[...] 是可选的)。

也就是说,在能够指定类型参数构造一个泛型类型之前,你必须首先指定它的open形式,这需要在类型名称之后以`<n> 的形式指定通用arity(类型参数的计数,<n>),即`2 在这种情况下System.Collections.Generic.Dictionary<TKey,TValue>(以 C# 表示法表示),使用 language-agnostic .NET API 表示法,如 this answer 中所述。

  • 如果不涉及嵌套类型(后缀+<typename>),如果指定了所有类型参数,则指定arity是可选;例如,代替[System.Collections.Generic.Dictionary`2[string, int]][System.Collections.Generic.Dictionary[string, int]] 就足够了。

但是,有问题的枚举器类型没有公共构造函数,所以你不能直接实例化它;相反,它是当您在封闭类型[System.Collections.Generic.Dictionary`2] (构造形式)上调用.GetEnumerator() 时返回的类型;通过以下方式验证:
Get-Member -InputObject ([System.Collections.Generic.Dictionary[string, int]])::new().GetEnumerator()

【讨论】:

    猜你喜欢
    • 2017-02-22
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 2017-09-18
    • 2017-04-19
    相关资源
    最近更新 更多