C#學習系列之泛型類

  因爲長時間在代碼中不使用泛型類,因此對泛型類的概念理解不是很深,最近在優化代碼的時候遇到了問題,發現用泛型類很是好解決,因此本身又從新寫了個列子加深理解。優化

  泛型:主要解決的問題是當一個類中的邏輯被多個地方調用,可是傳入的參數類型不一樣,此時使用泛型就可以解決複製方法的問題,讓咱們的代碼逼格更高。this

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 
 8 namespace Generic
 9 {
10     public class Program
11     {
12         static void Main(string[] args)
13         {
14             Console.WriteLine("------此示例是演示泛型的使用--------");
15             var a = new PersonA();
16             a.name = "張三";
17             var client = new Client<PersonA, PersonA>(a);
18             client.say();
19             Console.WriteLine("----------------");
20             client.run();
21             Console.WriteLine("----------------");
22             var b = new Dog();
23             b.name = "小黑";
24             var dog = new Client<Dog, Dog>(b);
25             dog.say();
26             Console.WriteLine("----------------");
27             dog.run();
28             Console.ReadLine();
29         }
30     }
31 
32     public class Dog : Person, IPerson
33     {
34 
35         public void Run()
36         {
37             Console.WriteLine(string.Format("{0}正在跑步...", this.name));
38         }
39 
40         public void Say()
41         {
42             Console.WriteLine(string.Format("{0}正在叫...", this.name));
43         }
44     }
45 
46     public class Person
47     {
48         public string name { get; set; }
49         public int age { get; set; }
50 
51     }
52 
53     public class PersonA : Person, IPerson
54     {
55 
56         public void Run()
57         {
58             Console.WriteLine(string.Format("{0}正在跑步...", this.name));
59         }
60 
61         public void Say()
62         {
63             Console.WriteLine(string.Format("{0}正在說話...", this.name));
64         }
65     }
66 
67     public interface IPerson
68     {
69         void Run();
70         void Say();
71     }
72 
73     public class Client<T, V>
74         where T : Person, IPerson
75     {
76         public Client(T t)
77         {
78             this.current = t;
79         }
80         public T current { get; set; }
81 
82         public void say()
83         {
84             current.Say();
85         }
86 
87         public void run()
88         {
89             current.Run();
90         }
91     }
92 
93 }
相關文章
相關標籤/搜索