MakeGenericType方法,運行時傳入泛型T參數,動態生成泛型類


在某些應用情況下,泛型T並非在代碼中寫入,而需要根據不同的情況去動態填入,微軟也提供了相應生成的方法:Type.MakeGenericType

 

方法傳入Type參數來替代泛型類參數,話不多說上代碼。先創建一個接口,定義print方法,在下面的實現方法中輸出“T”的類型

 

   public interface ITest
    {
        void print();
    }

    public class Test<T> : ITest
    {
        public void print()
        {
            Console.WriteLine(typeof(T).Name);
        }
    }

 

在主函數中編寫測試,依次測試如何創建泛型類,通過輸出類型來判斷

        public static void Main()
        {
            Type type = typeof(Test<>);
            ITest test;

            //Int32
            Type tInt32 = type.MakeGenericType(GetInt32());
            test = Activator.CreateInstance(tInt32) as ITest;
            test.print();

            //Int64
            Type tInt64 = type.MakeGenericType(GetInt64());
            test = Activator.CreateInstance(tInt64) as ITest;
            test.print();

            Type tString = type.MakeGenericType(GetString());
            test = Activator.CreateInstance(tString) as ITest;
            test.print();

            Console.Read();
        }

        static Type GetInt32()
        {
            return typeof(Int32);
        }

        static Type GetInt64()
        {
            return typeof(Int64);
        }

        static Type GetString()
        {
            return typeof(String);
        }

最終結果,等同於依次生成了tInt32(Test<Int32>),tInt64(Test<Int64>),tString(Test<String>),輸出如下:

 

此功能可適用於很多類型未知但需要泛型的場合,例如ORM框架中的類型映射轉換等等

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM