泛型約束
泛型約束是使用where
關鍵字讓泛型的類型有一定的限制
where T:struct
:結構類型的約束,只能接收結構類型作為泛型1
2
3
4
5
6
7
8
9
10class Test1<T> where T:struct
{
public T value;
public void TestFun<K>(K v) where K: struct
}
// 這句會報錯,因為他不是結構類型
//-- Test1<object> t = new Test1<object>();
// 這句可以
Test1<int> t2 = new Test1<int>();where T:class
:引用類型約束1
2
3
4
5
6
7
8
9
10
11class Test2<T> where T : class
{
public T value;
public void TestFun<K>(K k) where K : class {}
}
// 這句可以
Test2<object> t = new Test2<object>();
// 這句會報錯,因為 int 不是引用類型
//-- Test2<int> t2 = new Test2<int>();where T: new()
:這個泛型一定要有一個無參數public
的建構子(constructor
),此外若是組合使用的話new()
要放到最後1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16class Test3<T> where T : new()
{
public T value;
}
class PubC1 {}
class PubC2
{
public PubC2(int i) {}
}
// 這句可以
Test3<PubC1> t = new Test3<PubC1>();
// 這句不可以,因為 PubC2 沒有無參數的 public 建構子
//-- Test3<PubC2> t2 = new Test3<PubC2>();where T: 類名
:泛型參數必須要是其類或者是其子類where T: 介面名
:泛型參數必須要是其介面的衍伸類型where T:U
:泛型參數為另一個泛型本身或是其衍伸類型1
2
3class Test6<T,U> where T:U{
public T value;
}多個泛型皆有約束
1
class Test8<K,V> where K:class,new() where K:struct{}