泛型是.NET Framework2.0新增的一個(gè)特性,在命名空間System.Collections.Generic,包含了幾個(gè)新的基于泛型的集合類。
泛型解決了類型安全和裝箱問(wèn)題。
- 類型安全: 在編譯時(shí)驗(yàn)證對(duì)于泛型數(shù)據(jù)類型的操作,明確禁止那些可能在運(yùn)行時(shí)出錯(cuò)的行為。
- 在參數(shù)為object引用時(shí),避免對(duì)值類型進(jìn)行裝箱。
例如:
ArrayList emp = new ArrayList(7);
emp.add("hello");
emp.add("world");
emp.add(32);
上面的代碼不僅添加了不同類型的數(shù)據(jù)作為一個(gè)列表。然而,如果使用泛型List<T>則不會(huì)出現(xiàn)類似的情況。泛型集合是類型安全的,不允許存儲(chǔ)不匹配的元素,并且不會(huì)對(duì)值類型裝箱。
例如,當(dāng)你定義了一個(gè)List<string>, 該列表中便約束了你的數(shù)據(jù)類型,如下顯示:


泛型約束

參考: C#泛型約束 - 雨文木可 - 博客園
泛型的使用有系統(tǒng)自定義的一些泛型類型,泛型方法,泛型委托等,也可以自定義泛型的使用。
Demo
以下做了一個(gè)小Demo,分別是泛型類下使用泛型方法和非泛型方法, 非泛型類下使用非泛型方法和泛型方法。
Code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenericTest
{
class Program
{
static void Main(string[] args)
{
GenericClass<int> class1 = new GenericClass<int>();
class1.Say();
class1.Say(8);
GenericClass2 class2 = new GenericClass2();
class2.Say();
class2.Say<int>(8);
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenericTest
{
public class GenericClass<T>
{
public void Say()
{
// do nothing
}
public void Say(T t1)
{
Console.WriteLine($"{t1}");
}
}
public class GenericClass2
{
public void Say()
{
// do nothing
}
public void Say<T>(T t1)
{
Console.WriteLine($"{t1}");
}
}
}
Result:
