C# 泛型接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericInterface1
{
    class Program
    {
        public interface MyGenericInterface<T>
            //T 是類型參數。在實例化泛型的時候,可以使用約束對參數類型的種類進行限制。
            //定義一個泛型接口,泛型接口的聲明與普通接口的聲明的唯一區別是增加了一個T
            //泛型類型聲明所實現的接口必須對所有可能的構造類型都保持唯一。
            //否則就無法確定該爲某些構造類型調用哪個方法。
        {
            T Create();//接口調用Create方法。
        } 
        //實現上面泛型接口的泛型類
        //派生約束where T:TI(T要繼承TI)
        //構造函數約束where T:new(可以實例化)
        public class Factory<T,TI>:MyGenericInterface<TI> where T : TI, new()
        {
            //public TI Create()
            //{
            //    throw new NotImplementedException();
            //}

            public TI  Create()
            {
                return new T();
            }
        }
            
        static void Main(string[] args)
        {
            MyGenericInterface<System.ComponentModel.IListSource> facktory = 
            new Factory<System.Data.DataTable, System.ComponentModel.IListSource>();
            //輸出指定泛型的類型。
            Console.WriteLine(facktory.Create().GetType().ToString());
            Console.ReadLine();
        }
    }
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章