天天看點

C#——自定義泛型典例實戰

using System;
using System.Collections.Generic;
using System.Text;

namespace 自定義泛型
{
    /// <summary>
    /// @author ZJC
    /// 1.自定義泛型類
    /// 2.自定義泛型接口,封閉類型、開放類型介紹
    /// 3.泛型限制
    /// 泛型的目的也是為了代碼重用
    /// </summary>
    class Program
    {
        //
        //class MyGeneric<T,K,L,D,C>
        //下面是一個自定義泛型類的執行個體
        class MyGeneric<T>
        {
            public class Car
            {
                Car()
                {
                    Console.WriteLine("Car...");
                }            
            }
            public class Course
            {
                Course()
                {
                    Console.WriteLine("course...");
                }
            }
            public MyGeneric(int len)
            {
                arr = new T[len];
            }
            private T[] arr;
            public T this[int index]        //索引器
            {
                get
                { 
                    return arr[index];
                }
                set
                {
                    arr[index] = value;
                }
            }
        }
        //以下是:自定義泛型接口  執行個體
        public interface ITest<T>
        {            
            void M1(T t);            
        }
        public class MyGeneric2 : ITest<string>     //封閉類型,固定為string
        {

            public MyGeneric2()
            {
                Console.WriteLine("kk");
            }
            public void M1(string t)
            {
                Console.WriteLine(t);
            }
        }
        public class MyGeneric3<T> : ITest<T>       //開放類型,類型不固定
        {          
            public void M1( T t)             
            {
                Console.WriteLine(t.GetType());
            }
        }
        //泛型限制
        public class Person<T, T1, T2>
            where T : struct
            where T1 : class
            where T2 : new()
            //限制了T 必須是【值類型】,T1 必須是【引用類型】,T2這個類型必須帶有無參構造函數,要求構造函數不能為私有且類型不能是抽象的。
        {
            public T age
            {
                get;
                set;
            }
            public T1 Mycourse
            {
                get;
                set;
            }
            public T2 Mycar
            {
                get;
                set;
            }
        }        
        static void Main(string[] args)
        {
            MyGeneric<string> test = new MyGeneric<string>(3);
            test[0] = "成龍";
            test[1] = "李連傑";
            test[2] = "甄子丹";
            Console.WriteLine(test[0]+"\n"+test[1]+"\n"+test[2]);
            MyGeneric2 test2 = new MyGeneric2();
            test2.M1("自定義泛型接口");
            MyGeneric3<int> test3 = new MyGeneric3<int>();
            test3.M1(5);
            Person<int,MyGeneric2,MyGeneric2> test4 = new Person<int,MyGeneric2,MyGeneric2>();
        }
    }
}
           

繼續閱讀