Generics are easy to use. In powershell 2.0, the generic definition method is also very simple. The following describes how to use 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 # Use get-member to view the $ Foo method and attributes
8 get-member-inputobject $ foo
If you need a dictionary with two parameters:
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 # Use get-member to view the $ Foo method and attributes
10 get-member-inputobject $ foo
To facilitate the definition of generic variables, you can create some methods and use them very easily.
1 # create a list variable
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 # create a dictionary variable
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}
In this way, it is very simple to use:
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