约束泛型

约束泛型

代码:

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

运行结果:


技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
我创建了一个.NET开发交流群,用于分享学习心得和讨论相关技术难题。欢迎有兴趣的小伙伴扫码入群,相互学习!

原文地址:https://www.cnblogs.com/wml-it/p/14818623.html