C# 泛型函数-2.泛型约束

时间:2024-06-07 22:36:20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyGeneirc
{

    public class Constraint
    {

        /// <summary>
        /// 泛型约束
        /// 1.权利 可以使用基类的一切属性方法
        /// 2.义务 强制保证T 一定是People 或 其子类(不能是密封类,)
        /// </summary>
        public static void Show<T>(T tParam)
            where T : People, ISports // 基类约束
        {
            Console.WriteLine("当前类:{0},ID:{1}, Name:{2}",
                typeof(Constraint), tParam.Id, tParam.Name);

            tParam.Hi();

        }

        // 泛型约束相比父类 可以叠加,更加灵活
        public static void ShowBase(People tParam)
        {
            Console.WriteLine("当前类:{0},ID:{1}, Name:{2}",
                typeof(Constraint), tParam.Id, tParam.Name);

            tParam.Hi();
        }

        public static T Get<T>(T t)
            where T : ISports // 接口约束
        {
            t.Pinpang();
            return t;
        }

        public static T GetClass<T>(T t)
                where T : class // 引用类型约束
        {
            T tNew = null; // T 必须是引用类型
            return t;
        }

        public static T GetStruct<T>(T t)
                where T : struct // 值类型约束
        {
            // 默认类型 根据T的不同 赋予默认值
            T tNew = default(T); // T 必须是值类型
            return t;
        }

        public static T GetNew<T>(T t)
            where T : new() // 无参数构造函数约束
        {
            // new 对象
            T tNew = new T(); // T 类必须有构造函数(无参数)
            return t;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyGeneirc
{
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {

                People people = new People() { Id = 123, Name = "张三" };
                Chinese chinese = new Chinese() { Id = 234, Name = "李四" };
                Hubei hubei = new Hubei() { Id = 456, Name = "王五" };
                Japanese japanese = new Japanese() { Id = 678, Name = "田中" };



                Console.WriteLine("****************约束基类***********************");
                //Constraint.Show<People>(people);
                Constraint.Show<Chinese>(chinese);
                Constraint.Show<Hubei>(hubei);
                //Constraint.Show<Japanese>(japanese); // 编译报错

                Console.WriteLine("****************约束接口***********************");
                Constraint.Get<Chinese>(chinese);

            }
            catch(Exception ex) 
            {
                Console.WriteLine(ex.ToString());
            }

            Console.ReadLine();
        }
    }
}

在这里插入图片描述