泛型

本文通过几个具体的示例介绍了C#中泛型及其不同约束的应用方式,包括使用泛型方法处理不同类型的数据,并展示了如何根据不同约束展示不同类型的信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

泛型约束小计:

 

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             {
 6                 var generice = new GenericClass();
 7            
 8                 generice.ShowInt(11);
 9                 generice.ShowDateTime(DateTime.Now);
10                 generice.ShowPeople(new People {Id = 11, Name = "Tom"});
11             }
12 
13             {
14                 Console.WriteLine("---------------------------------------");
15                 var generice = new GenericClass2();
16                 generice.ShowObj(11);
17                 generice.ShowObj(DateTime.Now);
18                 generice.ShowObj(new People {Id = 11, Name = "Tom"});
19             }
20 
21             {
22                 Console.WriteLine("---------------------------------------");
23                 var generice = new GenericClass3();
24                 generice.ShowT<int>(11);
25                 generice.ShowT<DateTime>(DateTime.Now);
26                 generice.ShowT<People>(new People { Id = 11, Name = "Tom" });
27             }
28 
29             Console.ReadKey();
30         }
31     }
32     public class GenericClass3
33     {
34         public void ShowT<T>(T t)
35         {
36             Console.WriteLine("ShowT print {0},ShowT Parament Type Is {1}", t, t.GetType());
37         }
38     }
39 
40     public class GenericClass2
41     {
42         public void ShowObj(object obj)
43         {
44             Console.WriteLine("ShowObj print {0},ShowObj Parament Type Is {1}", obj, obj.GetType());
45         }
46     }
47 
48     public class GenericClass
49     {
50         public void ShowInt(int n)
51         {
52             Console.WriteLine("ShowInt print {0},ShowInt Parament Type Is {1}", n, n.GetType());
53         }
54         public void ShowDateTime(DateTime dt)
55         {
56             Console.WriteLine("ShowDateTime print {0},ShowDateTime Parament Type Is {1}", dt, dt.GetType());
57         }
58         public void ShowPeople(People people)
59         {
60             Console.WriteLine("ShowPeople print {0},ShowPeople Parament Type Is {1}", people, people.GetType());
61         }
62     }
63 
64     public class People
65     {
66         public int Id { get; internal set; }
67         public string Name { get; internal set; }
68     }
View Code

 

转载于:https://www.cnblogs.com/bhfdz/p/8952707.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值