挖土

Coding for fun.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

PowerShell 中定义和使用泛型

Posted on 2010-07-30 11:27  挖土.  阅读(1083)  评论(0编辑  收藏  举报

泛型用起来很方便,在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