使用泛型能够最大限度的重用代码,保护类型安全,提高性能
泛型成员因为类型的不确定性,不能使用算术运算符、比较运算符
泛型参数可以有多个,可以是编译器能够识别的任何类型
类型参数的名字不能随便起,不能重名
using System;
namespace 泛型类
{
class SwapTwoNumber<T>
{
//T只是占位符,T只可以赋值,但是不能运算 + - * /
// public void Swap(ref T num1,ref T num2)
// {
// T temp = default(T);
// temp = num1;
// num1 = num2;
// num2 = temp;
// }
//演示泛型限定
//strcut 表示限定的是值类型
// public void Swap<T>(ref T num1,ref T num2) where T:struct
// {
// T temp = default(T);
// temp = num1;
// num1 = num2;
// num2 = temp;
// }
//演示引用类型限定
//class 表示限定的是引用类型
// public void Swap<T>(ref T num1,ref T num2) where T:class
// {
// T temp = default(T);
// temp = num1;
// num1 = num2;
// num2 = temp;
// }
public T Swap<T>(ref T num1,ref T num2) where T:IComparable
{
// char c = (char)num1;
// char c2 = (char)num2;
// Console.WriteLine(c);
// Console.WriteLine (c2);
// return num1>num2?num1:num2;
if (num1.CompareTo (num2) < 0) {
return num2;
} else {
return num1;
}
}
}
class MainClass
{
public static void Main (string[] args)
{
// int a = 10;
// int b = 9;
// new SwapTwoNumber ().Swap (ref a, ref b);
// Console.WriteLine ("交换后a的值{0},b的值{1}", a, b);
//
// //演示int类型
// new SwapTwoNumber<int> ().Swap (ref a, ref b);
// Console.WriteLine ("交换后a的值{0},b的值{1}", a, b);
//演示float
// float f1 = 10.0f;
// float f2 = 9.0f;
// new SwapTwoNumber<float> ().Swap (ref f1, ref f2);
// Console.WriteLine ("交换后f1的值{0},f2的值{1}", f1, f2);
//演示string
// string s1 = "中国";
// string s2 = "马志龙";
// new SwapTwoNumber<string> ().Swap (ref s1, ref s2);
// Console.WriteLine ("交换后s1的值{0},s2的值{1}", s1, s2);
//
// string s1 = "A"; //65
// string s = "a"; //97
//
// //返回为0 意味着相等
// //返回1 表示降序
// //返回-1 表示升序
// int isBig = s1.CompareTo (s);
// Console.WriteLine (isBig);
// int a = 10;
// int b = 9;
// int max = new SwapTwoNumber<int> ().Swap (ref a, ref b);
// Console.WriteLine (max);
}
}
}