using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace generic
{
class Test<T1, T2>//构造泛型类,T1,T2为类型参数
{
public T1 var1;
public T2 var2;
public void print()
{
Console.WriteLine("var1:{0} var2:{1}", var1 , var2);
}
}
class Program
{
static void Main(string[] args)
{
//两种实例化的方式,效果相同
Test<int,string> first = new Test<int, string>();//int和string为类型实参,分别对应T1,T2
var second = new Test<string, int>();
first.var1 = 123; //first中,var1只能为int类型,当然也可以通过强制类型转换成其他的类型了
first.var2 = "Good Luck!"; //只能为string类型,同上
first.print();
second.var1 = "hello world";
second.var2 = 345;
second.print();
Console.ReadKey();
}
}
}
泛型接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace generic
{
interface Test
{
void Print(T value);
}
/*
* 泛型的接口实现必须唯一,必须保证类型参数组合不会再类型中产生两个重复的接口
* class Simple<S> : Test<int>, Test<S> 是错误的,因为S有可能是int类型
* 你也可以再非泛型类型中实现泛型接口
* class Simple : Test<int>, Test<string>
*/
class Simple<S> : Test<S>
{
public void Print(S value)
{
Console.WriteLine("value is {0}",value);
}
}
class Program
{
static void Main(string[] args)
{
var IntSimp = new Simple<int>();
var StrSimp = new Simple<string>();
IntSimp.Print(123);
StrSimp.Print("hello world");
Console.ReadKey();
}
}
}
本文档展示了C#中泛型类和泛型接口的使用。通过创建带类型参数的Test类并实例化,演示了如何限制成员变量的类型以及调用方法。同时,解释了泛型接口的约束,确保类型参数的唯一性,并提供了一个Simple类作为泛型接口的实现。示例代码包括实例化和调用Print方法的过程。
1042

被折叠的 条评论
为什么被折叠?



