C#: the sample usage of c# template

本文通过具体的代码示例介绍了如何在C#中使用泛型约束来限制泛型参数的类型,并展示了如何覆盖基类的方法以实现特定的功能。此外,还提供了静态方法使用泛型的例子。

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

1. class definition with constraints

 

1 class Test<T, V> where V:MyType {
2         public String name;
3         public T value;
4         public virtual void print() {
5             Console.WriteLine("{0}={1}", name, value);
6         }//print()
7     } //class

 

2. inherited class definition with constraint( my use constraint)

 

1     
2     class Test2<T1,T2>  : Test<T1,T2>  where T2:MyType{
3         public override void print() {
4             Console.WriteLine("IN Test2");
5             base.print();
6         }//print()
7         
8     }

 

3. template in method(static and non-static)

 

1         public static void testme<T>(T val) where T:IHoho, IOK{
2             Console.WriteLine(val);
3         }
4         public void testme2<T>(T val) {
5             Console.WriteLine(val);
6         }

 

4. Usage

 

 1         public static void Main(string[] args)
 2         {
 3             Test<int, MyType2> intValue = new Test<int, MyType2>();
 4             intValue.name = "int";
 5             intValue.value = 100;
 6             intValue.print();
 7             Test2<float, MyType2> floatValue = new Test2<float, MyType2>();
 8             floatValue.name = "float";
 9             floatValue.value = 200.10F;
10             floatValue.print();
11             testme(new MyType2(100));
12             testme(new MyType2("Hello"));
13             new Program().testme2("World");
14             
15         }

 

 

转载于:https://www.cnblogs.com/sliencer/archive/2012/10/23/2736418.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值