C#学习系列之泛型类

  由于长时间在代码中不使用泛型类,所以对泛型类的概念理解不是很深,最近在优化代码的时候遇到了问题,发现用泛型类非常好解决,所以自己又重新写了个列子加深理解。

  泛型:主要解决的问题是当一个类中的逻辑被多个地方调用,但是传入的参数类型不同,此时使用泛型就能够解决复制方法的问题,让我们的代码逼格更高。

 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 }
原文地址:https://www.cnblogs.com/manyiString/p/7120246.html