惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
博客园_首页
量子位
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
H
Help Net Security
The Cloudflare Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
A
About on SuperTechFans
腾讯CDC
H
Hackread – Cybersecurity News, Data Breaches, AI and More
D
DataBreaches.Net
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
Jina AI
Jina AI
月光博客
月光博客
云风的 BLOG
云风的 BLOG
博客园 - 聂微东
Hugging Face - Blog
Hugging Face - Blog
雷峰网
雷峰网
C
Check Point Blog
V
V2EX
T
Tailwind CSS Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Microsoft Security Blog
Microsoft Security Blog

博客园 - 挖土.

学笛子 PowerShell: Try...Catch...Finally 实现方法 How to set the compuder to auto login 让 PowerShell 2.0 支持 DotNet FrameWork 4.0 用 Powershell 安装Dotnet FrameWorrk 4.0 PowerShell 调用.netFramework中的静态函数 PowerGUI Visual Studio is now in beta! PowerShell 如何引用DLL PowerShell中Add-Content 和 Out-File 的区别 给string加几个扩展方法 加快 c++ Builder 5编译速度 Windows 7 下的 SUBST 命令 How to configure the BDE for Windows Vista/7 - 挖土. Linker problems with Borland builder SQL 中的中位值计算 Windows 7的“上帝模式” XML 序列化和反序列化详例代码 给存储过程传递一个表 VSIdeTesthost installation issue - 挖土.
PowerShell 中定义和使用泛型
挖土. · 2010-07-30 · via 博客园 - 挖土.

泛型用起来很方便,在PowerShell 2.0的版本中,泛型的定义方法也很简单。下面看看List的使用方法:

1 $foo = New-Object 'System.Collections.Generic.List[int]'
2 $foo.Add(10)
3 $foo.Add(20)
4 $foo.Add(30)
5 $foo
6 
7 #使用Get-Member查看$foo的方法和属性
8 Get-Member -InputObject $foo

如果是需要两个参数的Dictionary:

 1 $foo = New-Object 'System.Collections.Generic.Dictionary[string,string]'
 2 $foo.Add('FOO','BAR')
 3 $foo.Add('FOB','MENU')
 4 $foo.Add('FOC','MOUSE')
 5 $foo.('FOO')
 6 $foo.Item('FOO')
 7 $foo
 8 
 9 #使用Get-Member查看$foo的方法和属性
10 Get-Member -InputObject $foo

 为了方便定义泛型的变量,可以建立一些方法,使用起来就会非常简单。

 1 # 创建List变量
 2 Function global:New-GenericList([type] $type)
 3 {
 4     $base = [System.Collections.Generic.List``1]
 5     $qt = $base.MakeGenericType(@($type))
 6     New-Object $qt
 7 }
 8 
 9 # 创建Dictionary变量
10 Function global:New-GenericDictionary([type] $keyType, [type] $valueType)
11 {
12     $base = [System.Collections.Generic.Dictionary``2]
13     $qc = $base.MakeGenericType(($keyType$valueType))
14     New-Object $qc
15 }

这样子使用起来就非常简单了:

 1 PS D:\> $intList = New-GenericList int
 2 PS D:\> $intList.Add(10)
 3 PS D:\> $intList.Add(20)
 4 PS D:\> $intList.Add(30)
 5 PS D:\> $intList
 6 10
 7 20
 8 30
 9 
10 PS D:\> $gd = New-GenericDictionary string int
11 PS D:\> $gd["Red"= 1
12 PS D:\> $gd["Blue"= 2
13 PS D:\> $gd
14 
15 Key          Value
16 ---          -----
17 Red              1
18 Blue             2