C#中,泛型约束就是将泛型的变量类型约束在某些范围之内,而不是允许去自主指定任何类型;
基本语法为
class 类名<泛型字符1,泛型字符2> where 泛型字符1 : 泛型约束类型1 where 泛型字符2 : 泛型约束类型2 .......{}
主要包括以下几类:
cs
using System;
namespace lesson06
{
//约束泛型的变量类型为值类型 where 泛型字符 : struct
class Test<T> where T : struct
{
public T value;
public void TestFun<K>(K v) where K : struct
{
Console.WriteLine(v);
}
}
//约束泛型的变量类型为引用类型 where 泛型字符 : class
class Test2<T> where T : class
{
public T value;
public void TestFun2<K>(K v) where K : class
{
}
}
//约束泛型的变量类型为存在公有无参构造函数的非抽象类类或结构体 where 泛型字符 : new()
class Test3<T> where T : new()
{
public T value;
public void TestFun<K>(K v) where K : new()
{
Console.WriteLine(v);
}
}
class Test3_1
{
public Test3_1 () {}
}
class Test3_1_1 : Test3_1 { }
//约束泛型的变量类型为某一特定的类及其派生类 where 泛型字母 : 类或其派生类类名
class Test4<T> where T : Test3_1
{
public T value;
public void TestFun<K>(K v) where K : Test3_1
{
Console.WriteLine(v);
}
}
//约束泛型的变量类型为某接口或其派生类 where 泛型字母 : 接口或其派生
interface IFly { }
class TestIFly : IFly { }
class Test5<T> where T : IFly
{
public T value;
public void TestFun<K>(K v) where K : IFly
{
Console.WriteLine(v);
}
}
//约束泛型的变量类型为另一个泛型类及其派生
//where 泛型字母(代表本身或其派生) : 另一个泛型字母(代表本身)
class Test6<T, U> where T : U
{
public T value;
public void TestFun<K,V>(K v) where K : V
{
Console.WriteLine(v);
}
}
//约束的组合使用
class Test7<T> where T : class, new()
{
}
//多泛型约束
class Test8<T, K> where T : class, new() where K : struct
{
}
class Program
{
static void Main(string[] args)
{
//约束为值类型
Test<int> t1 = new Test<int>();
t1.TestFun<float>(1.3f);
//约束为存在无参构造类或结构体类型
Test3<Test3_1> t3 = new Test3<Test3_1>();
//约束为具体类及其派生
Test4<Test3_1> t4_1 = new Test4<Test3_1>();
Test4<Test3_1_1> t4_2 = new Test4<Test3_1_1>();
//约束为具体接口及其派生
Test5<IFly> t5_1 = new Test5<IFly>();
Test5<TestIFly> t5_2 = new Test5<TestIFly>();
//约束双泛型为本身与派生(前是后的本身或派生)
Test6<TestIFly,IFly> t6 = new Test6<TestIFly,IFly>();
}
}
}
约束允许组合使用,在有多个泛型需要添加约束时,直接用where连接即可。