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);


        }
复制代码

 

posted @   Wen_Chen  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示