C# 2.0 出现后,最让我心动的特性就是 Generic 了,最近刚刚开始研究,写了个简单的小例子,顺手传上来,与大家共享。
运行后的输出结果如下:
这只是最基本的用法,以后再继续深入。。。
1using System;
2using System.Collections.Generic;
3
4public class GenericTest
5{
6 public static void Main()
7 {
8 // Initialize
9 User user1 = new User();
10 user1.ID = 1;
11 user1.Name = "User1";
12
13 User user2 = new User();
14 user2.ID = 2;
15 user2.Name = "User2";
16
17 // List<T> Test
18 IList<User> list = new List<User>();
19 list.Add(user1);
20 list.Add(user2);
21
22 Console.WriteLine("IList<T> Test:");
23 foreach (User user in list)
24 {
25 Console.WriteLine(user.ToString());
26 }
27 Console.WriteLine();
28
29 // IDictionary<TKey, TValue> Test
30 IDictionary<int, User> dic = new Dictionary<int, User>();
31 dic.Add(user1.ID, user1);
32 dic.Add(user2.ID, user2);
33
34 Console.WriteLine("IDictionary<TKey, TValue> Test:");
35 foreach (KeyValuePair<int, User> kv in dic)
36 {
37 Console.WriteLine(kv.Key.ToString() + "--" + kv.Value.ToString());
38 }
39 }
40}
41
42public class User
43{
44 int id;
45 string name;
46
47 public int ID
48 {
49 get
50 {
51 return id;
52 }
53 set
54 {
55 id = value;
56 }
57 }
58
59 public string Name
60 {
61 get
62 {
63 return name;
64 }
65 set
66 {
67 name = value;
68 }
69 }
70
71 public override string ToString()
72 {
73 return "User:ID=" + id.ToString() + ",Name=" + name;
74 }
75}
76
2using System.Collections.Generic;
3
4public class GenericTest
5{
6 public static void Main()
7 {
8 // Initialize
9 User user1 = new User();
10 user1.ID = 1;
11 user1.Name = "User1";
12
13 User user2 = new User();
14 user2.ID = 2;
15 user2.Name = "User2";
16
17 // List<T> Test
18 IList<User> list = new List<User>();
19 list.Add(user1);
20 list.Add(user2);
21
22 Console.WriteLine("IList<T> Test:");
23 foreach (User user in list)
24 {
25 Console.WriteLine(user.ToString());
26 }
27 Console.WriteLine();
28
29 // IDictionary<TKey, TValue> Test
30 IDictionary<int, User> dic = new Dictionary<int, User>();
31 dic.Add(user1.ID, user1);
32 dic.Add(user2.ID, user2);
33
34 Console.WriteLine("IDictionary<TKey, TValue> Test:");
35 foreach (KeyValuePair<int, User> kv in dic)
36 {
37 Console.WriteLine(kv.Key.ToString() + "--" + kv.Value.ToString());
38 }
39 }
40}
41
42public class User
43{
44 int id;
45 string name;
46
47 public int ID
48 {
49 get
50 {
51 return id;
52 }
53 set
54 {
55 id = value;
56 }
57 }
58
59 public string Name
60 {
61 get
62 {
63 return name;
64 }
65 set
66 {
67 name = value;
68 }
69 }
70
71 public override string ToString()
72 {
73 return "User:ID=" + id.ToString() + ",Name=" + name;
74 }
75}
76
运行后的输出结果如下:
IList<T> Test:
User:ID=1,Name=User1
User:ID=2,Name=User2
IDictionary<TKey, TValue> Test:
1--User:ID=1,Name=User1
2--User:ID=2,Name=User2
User:ID=1,Name=User1
User:ID=2,Name=User2
IDictionary<TKey, TValue> Test:
1--User:ID=1,Name=User1
2--User:ID=2,Name=User2
这只是最基本的用法,以后再继续深入。。。