Files
Csharp/C#进阶/Lesson6_泛型约束/Program.cs
T

186 lines
4.2 KiB
C#
Raw Normal View History

2025-10-13 17:44:02 +08:00
namespace Lesson6_泛型约束
{
#region 知识回顾
//泛型类
class TestClass<T, U>
{
public T t;
public U u;
public U TestFun(T t)
{
return default(U);
}
//泛型函数
public V TestFun<K, V>(K k)
{
return default(V);
}
}
#endregion
#region 知识点一 什么是泛型约束
//让泛型的类型有一定限制
//关键字:where
//泛型约束一共有6种
//1.值类型 where 泛型字母:struct
//2.引用类型 where 泛型字母:class
//3.存在无参公共构造函数 where 泛型字母:new()
//4.某个类本身或其派生类 where 泛型字母:类名
//5.某个接口的派生类 where 泛型字母:接口名
//6.另一个泛型类本身或派生类 where 泛型字母:另一个泛型字母
#endregion
#region 知识点二 各泛型约束讲解
class Test1<T> where T : struct
{
public T v;
public void TestFun<K>(K v) where K : struct
{
}
}
class Test2<T> where T : class
{
public T value;
public void TestFun<K>(K v) where K : class
{
}
}
class Test3<T> where T: new()
{
public T value;
public void TestFun<K>(K v) where K : new()
{
}
}
class Test1
{
}
class Test2
{
public Test2(int i)
{
}
}
class Test4<T> where T : Test1
{
public T value;
public void TestFun<K>(K v) where K : Test1
{
}
}
class Test3 : Test1
{
}
interface IFly
{
}
class Test4 : IFly
{
}
class Test5<T> where T : IFly
{
public T value;
public void TestFun<K>(K v) where K : IFly
{
}
}
class Test6<T,U> where T : U
{
public T value;
public void TestFun<K,V>(K k) where K : V
{
}
}
#endregion
#region 知识点三 约束的组合使用
class Test7<T> where T : class, new()
{
}
#endregion
#region 知识点四 多个泛型有约束
class Test8<T,K> where T:class,new() where K : struct
{
}
#endregion
#region 总结
//泛型约束: 让类型有一定限制
//class
//struct
//new()
//类名
//接口名
//另一个泛型字母
//注意:
//1.可以组合使用
//2.多个泛型约束 用where连接即可
#endregion
internal class Program
{
static void Main(string[] args)
{
TestClass<string,int> t = new TestClass<string,int>();
t.t = "123fgd";
t.u = 10;
t.TestFun("123");
t.TestFun<float,double>(123);
//Test1<Object> t1 = new Test1<object>;//Object类型不能为空,所以报错
Test1<int> t1 = new Test1<int>();//int是值类型,所以可以放
//t1.TestFun<Random>();//不可为空同样报错
t1.TestFun<float>(1.3f);
//Test2<int> t2 = new Test2<int>;//因为是引用类型所以值类型int会报错
Test2<Random> t2 = new Test2<Random>();
t2.TestFun<string>("123");
t2.TestFun<Object>(new object());
t2.value = new Random();
Test3<Test1> t3 = new Test3<Test1>();//如果Test1的构造函数是私有也会报错
//Test3<Test2> t4 = new Test3<Test2>();//test2有参所以报错,如果test2是无参但抽象类也会报错,必须是有公共无参构造函数的非抽象类
//Test3<int> t4 = new Test3<int>();//没问题,struct值类型是默认有无参构造且不会被顶替的
Test4<Test3> t4 = new Test4<Test3>();//Test3是继承约束的Test1的类,所以也不会报错
Test5<IFly> t5 = new Test5<IFly>();
t5.value = new Test4();//继承IFly的Test4
Test6<Test4,IFly> t6 = new Test6<Test4, IFly> ();
Test6<Test4, Test4> tx = new Test6<Test4, Test4>();
}
}
}