34.为泛型参数设定约束
1.指定参数是值类型(除Nullable)外,可有如下形式:
public void Method<T> (T t) where T: struct{}
2.指定参数是引用类型,可有如下形式:
public void Methodl<T>(T t) where T: class{} //这个是直接class,传入任何类都可以调用这个方法且不出错
public void Methodl<T>(T t) where T:具体类名{} //只能传入具体的类名,但是不能传递接口转的实现类
注意:object不能用来作为约束。
4.指定参数必须是指定的基类,或者派生自指定的基类。
5.指定参数必须是指定的接口,或者实现指定的接口。
6.指定T提供的类型参数必须是为U提供的参数,或者派生自为U提供的参数:
class Sample<U>
{
public void Methodl<T>(T t) where T: U{}
}
7.可以对同一类型的参数应用多个约束,并且约束自身可以是泛型类型。
方法代码:
public static void GetInt<T>(T t) where T : struct { Console.WriteLine(t); } public static void GetPerson<T>(T t) where T : Person { Console.WriteLine(t.ToString()); } public static void GetCompany<T>(T t1, T t2) where T : Company { Console.WriteLine(t1.ToString() + t2.ToString()); } public static void InterfacePerson<T>(T t1) where T : IHuman { Console.WriteLine(t1.ToString()); }
主程序:
static void Main(string[] args) { Console.WriteLine("Hello World!"); Person person = new Person() { Name = "person", Age = 78 }; Company company01 = new Company() { Name = "Tencent", Address = "7654321" }; Company company02 = new Company() { Name = "Sunam", Address = "12345" }; Method.GetPerson(person); Method.GetCompany(company01, company02); Console.WriteLine(); Console.WriteLine("接口:"); IHuman human = new Person() { Name = "Human", Age = 44 }; Method.InterfacePerson(human); //Method.GetPerson(human); //该行报错,接口不能转实现类 Method.InterfacePerson(person); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】