Define and use generics in powershell

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.