C# 泛型

参考:C#中的泛型_morn to的博客-CSDN博客_c# 泛型

一、泛型

定义:泛型允许我们延迟编写类或方法中的参数类型,直到在程序中使用它的时候,模块内高内聚,模块间低耦合。

二、可空类型

对于引用类型的变量来说,如果未对其赋值,在默认情况下是 Null 值,对于值类型的变量,如果未赋值,整型变量的默认值为 0。

C# 语言中提供了一种泛型类型 (即可空类型 (System.Nullable<T>))来解决值类型的变量在未赋值的情况下允许为 Null的情况。

         static void Main(string[] args)
        {
            int? i = null;
            double? d = 3.14;
            if(i.HasValue)
            {
                Console.WriteLine("i的值为{0}", i);
            }
            if(d.HasValue)
            {
                Console.WriteLine("d的值为{0}", d);
            }
            Console.ReadLine();
        }    

三、泛型方法

         static void TestMethod<T>(T a,T b)
        {
            Console.WriteLine("参数1的类型是{0},参数2的类型是{1}", a.GetType(), b.GetType());
        }

四、带约束的泛型类

class Program
    {
        static void Main(string[] args)
        {
            TestClass<Student> testClass = new TestClass<Student>();
            testClass.Add(new Student() { Age = 21, Name = "YXZ" });
            testClass.Add(new Student() { Age = 25, Name = "YMW" });
            testClass.Show();
            Console.ReadLine();
        }
        static void TestMethod<T>(T a,T b)
        {
            Console.WriteLine("参数1的类型是{0},参数2的类型是{1}", a.GetType(), b.GetType());
        }
    }
    class TestClass<T> where T : Student
    {
        List<T> ts = new List<T>();
        public void Add(T t)
        {
            ts.Add(t);
        }
        public void Show()
        {
            foreach(var n in ts)
            {
                Console.WriteLine("{0},{1}", n.Age,n.Name);
            }
           
        }

    }
    class Student
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }

 

posted @ 2022-06-15 20:58  HelloWorld庄先生  阅读(1739)  评论(0编辑  收藏  举报