C#中的泛型

C#中的泛型

簡介:架構

    泛型,就是在定義方法時先不聲明方法的返回值類型或者參數類型,只是聲明佔位符,而是在調用方法時才聲明類型。泛型是延遲聲明的:即定義的時候沒有指定具體的參數類型,把參數類型的聲明推遲到了調用的時候才指定參數類型。 延遲思想在程序架構設計的時候很受歡迎。spa

案例:架構設計

class GenericMethod
    {
        static void Main(string[] args)
        {
            int iValue = 123;
            string sValue = "123";
            DateTime dtValue = DateTime.Now;

            Console.WriteLine("***********Generic***************");
            //調用泛型方法
            GenericMethod.Show<int>(iValue);
            GenericMethod.Show<string>(sValue);
            GenericMethod.Show<DateTime>(dtValue);
            Console.ReadKey();

        }
        //定義泛型
        public static void Show<T>(T tParameter)
        {
            Console.WriteLine("This is {0},parameter={1},type={2}",
                typeof(GenericMethod), tParameter.GetType().Name, tParameter.ToString());
        }
    }

執行結果:設計

***********Generic***************
This is lamba.GenericMethod,parameter=Int32,type=123
This is lamba.GenericMethod,parameter=String,type=123
This is lamba.GenericMethod,parameter=DateTime,type=2020/6/8 上午 09:39:34
相關文章
相關標籤/搜索