什么是 List`1 对象?

2023-11-26

System.IO.FileInfo 有一个 Target 成员。

Using Get-Item -Path * -Include 't.txt' | Get-Member显示它有一个Target成员是CodeProperty.

Using GetType()显示它是一个List`1

C:>Get-Item -Path * -Include 't.txt' | ForEach-Object { $_.Target.GetType() }

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     List`1                                   System.Object

C:>Get-Item -Path * -Include 't.txt' | % { $_.Target.GetType() | % { $_.FullName } }
System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

vonPryz在评论中提供了关键指针:List`1 is .NET 的表示泛型 named List具有数量(`) 1,即具有 1 个类型参数的泛型类型.

(指某东西的用途`在这种情况下与 PowerShell 的使用无关`作为转义字符)。

就你而言,System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]表明通用类型是closed(实例化)类型System.String.

抛开组装资格不谈(mscorlib, Version = ...), the 等效的 PowerShell 表示是System.Collections.Generic.List`1[[string]],但是可以通过两种方式简化:

  • 数量指标,`1,可以省略,因为元数是由类型参数隐含的[...], [string].
  • 鉴于只有1type参数,可以省略外层[...]围绕类型参数列表。

因此,您可以仅使用System.Collections.Generic.List[string],或者,表示为 PowerShell类型文字 ([...]), [System.Collections.Generic.List[string]]


可选阅读:在 PowerShell 中缩短类型名称和文字:

[System.Collections.Generic.List[string]]有点笨重,有两种方法可以缩短它:

  • PowerShell 允许您省略System.任何类型的命名空间的一部分, so [Collections.Generic.List[string]]也有效。

  • 电源外壳v5+提供using namespace陈述,类似于 C# 的using陈述:

      # Note:
      #  * `using namespace` must be at the *start* of the script (potentially
      #    preceded by other `using` statements and comments only)
      #  * The 'System.' part of a namespace must *not* be omitted.
      using namespace System.Collections.Generic
    
      [List[string]] # short for: [System.Collections.Generic.List[string]]
    

此外,PowerShell 还具有内置类型加速器对于某些常用类型,它们是引用特定类型的单组件名称,无需指定其来源名称空间;例如。,[xml]是一个类型加速器[System.Xml.XmlDocument].

这篇 TechNet 博客文章表明您可以使用以下命令列出所有内置类型加速器:

[psobject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::
  get.GetEnumerator() | Sort-Object Key

As 不可救药1指出,你甚至可以定义您自己的类型加速器::Add() method;例如,以下命令定义[cmdinfo]作为类型的加速器[System.Management.Automation.CommandInfo]:

[psobject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::
      Add('cmdinfo', [System.Management.Automation.CommandInfo])

新加速器即将上市全局会话(但仅适用于当前会话),即使调用是从子作用域进行的。

也就是说,有充分的理由not去做这个:

  • System.Management.Automation.TypeAccelerators is 不是公共类型,因此它不是 PowerShell 公共 API 的一部分,因此不能保证将来会存在(以其当前形式)。

  • 所以,the using namespace方法是可取的.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

什么是 List`1 对象? 的相关文章

随机推荐