约束泛型

约束泛型

代码:

namespace Demo5
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 20210527;
            string str = "Hello,2021-05-27";

            //MyTest1传入参数类型必须是引用类型,否则会编译时报错
            MyTest1<string>(str);

            //MyTest2传入参数类型必须是值类型,否则会编译时报错
            MyTest2<int>(number);

            Console.ReadKey();
        }

        //限定传入的参数类型是引用类型
        public static void MyTest1<T>(T t) where T : class
        {
            Console.WriteLine("{0} 的類型是{1}", t.ToString(), t.GetType());
        }

        //限定传入的参数类型是值类型
        public static void MyTest2<T>(T t) where T : struct
        {
            Console.WriteLine("{0} 的類型是{1}", t.ToString(), t.GetType());
        }
    }
   
}

运行结果:

 

posted @ 2021-05-27 16:49  码农阿亮  阅读(57)  评论(0编辑  收藏  举报