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

推荐订阅源

F
Fortinet All Blogs
爱范儿
爱范儿
V
Visual Studio Blog
Engineering at Meta
Engineering at Meta
B
Blog
云风的 BLOG
云风的 BLOG
G
Google Developers Blog
MongoDB | Blog
MongoDB | Blog
博客园 - Franky
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
WordPress大学
WordPress大学
D
DataBreaches.Net
B
Blog RSS Feed
小众软件
小众软件
人人都是产品经理
人人都是产品经理
I
InfoQ
P
Proofpoint News Feed
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
J
Java Code Geeks
The GitHub Blog
The GitHub Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报

博客园 - 挖土.

学笛子 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