/// 泛型
namespace _0817_ClassCode
{
/// 泛型需要注意的地方:
/// 1.T只是占位符,没有实际的意义,所以不能运用四则运算(+-*/),关系运算符
/// 2.T仅仅可以有赋值操作
/// 3.T可以限定的类型(常用的),值类型,引用类型,接口
/// 4.where T :struct 限定T为值类型
/// 5.where T:class 限定T为引用类型
/// 6.where T: 接口 限定实现接口
class Program
{
//T:struct 限定T的类型为值类型
public void Swap<T>(ref T a,ref T b) where T :struct
{
T c = default(T);
c = a;
a = b;
b = c;
}
//限定多个参数
public void Show<U,O>(U a,O b)where U:struct where O:class
{
Console.WriteLine(a);
Console.WriteLine(b);
}
//演示接口限定
//如果一个泛型T有多个限定,那么class和struct要放在最前面
public T Comp<T>(T a,T b)where T:class,IComparable
{
if (a.CompareTo(b) < 0)
{
return b;
}
else
{
return a;
}
}
static void Main(string[] args)
{
int a = 10;
int b = 20;
//当T限定为引用类型的时候,调用下列代码会出现编译错误
new Program().Swap<int>(ref a, ref b);
Console.WriteLine("a的值{0} b的值{1}",a,b);
//交换string类型变量
string s1 = "1";
string s2 = "2123465";
//当T限定为值类型的时候,调用下面代码会出现编译错误
// new Program().Swap<string>(ref s1, ref s2);
// Console.WriteLine("s1:{0},s2:{1}",s1,s2);
//比较两个字符串,返回比较大的
string str= new Program().Comp<string>(s1, s2);
Console.WriteLine(str);
Console.ReadKey();
}
}
}
初识c#---泛型
最新推荐文章于 2021-10-06 10:56:46 发布