泛型就是将类型做参数
泛型约束
T:struct |
类型参数必须是值类型。可以指定除 Nullable 以外的任何值类型。 有关更多信息,请参见 使用可以为 null 的类型(C# 编程指南)。 |
T:class |
类型参数必须是引用类型;这一点也适用于任何类、接口、委托或数组类型。 |
T:new() |
类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时, new() 约束必须最后指定。 |
T:<基类名> |
类型参数必须是指定的基类或派生自指定的基类。 |
T:<接口名称> |
类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。 |
T:U |
为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数。这称为裸类型约束。 |
泛型的应用
泛型类,泛型方法,泛型接口,泛型委托,泛型集合
一句话讲,需要数据类型的地方就可以用泛型
常用泛型设计一些通用(基于不同类型的复用)的算法。
练习案例↓ ab互换
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace DemoGenric
{
class GenricBase1
{
static void Main2(string[] args)
{
My<int> myobj = new My<int>();
myobj.Add(1);
//myobj.Add("aa");//更安全,第一时间告诉 放的不合适
myobj.Add(2); //不需要类型转换 性能更好; object<int 很多 性能
myobj.Add(3);
myobj.Add(4);
}
static void Main1(string[] args)
{
My<int> myobj = new My<int>();
myobj.Add(1);
My<String> myobj2 = new My<String>();
myobj2.Add("aa");
Your your1 = new Your();
//your1.Add<int>(1);
//your1.Add<int>(2);
your1.Add(1);
your1.Add(2);
}
static void Main3(string[] args)
{
string a = "aas";
string b = "bb";
Console.WriteLine(a);
Console.WriteLine(b);
My<string> my = new My<string>();
my.Swap(ref a, ref b);
//Fun????
Console.WriteLine(a);
Console.WriteLine(b);
Console.ReadKey();
}
}
//class My
//{
// ArrayList arrList = new ArrayList();//
// public void Add(int i)
// {
// arrList.Add(i);
// }
//}
class My<T>
{
ArrayList arrList = new ArrayList();//
public void Add(T i)
{
arrList.Add(i);
}
public void Swap(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
}
class Your
{
ArrayList arrList = new ArrayList();//
public void Add<T>(T i)
{
arrList.Add(i);
}
public void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
}
}
泛型约束 where
namespace DemoGenric2
{
class GenricBase2
{
static void Main11()
{
//My<int> my1 = new My<int>();
//My<NormalizationForm> my11 = new My<NormalizationForm>();
//My<string> my2 = new My<string>();
My<Dog> my3 = new My<Dog>();
}
}
//class My<T> where T:struct //值类型:枚举 结构
//{
//}
//class My<T> where T : class //引用类型:类,接口,委托
//{
//}
class My<T> where T :Animal,IFly
{
}
interface IFly
{ }
class Animal
{ }
class Dog:Animal,IFly { }
}