c# 動態實例化一個泛型類


轉載:http://www.cnblogs.com/lcyhjx/p/7444179.html

動態實例化一個類,比較常見,代碼如下

復制代碼
namespace ConsoleApp2
{
    public class MyClass
    {

    }
}
復制代碼
Type classType = Type.GetType("ConsoleApp2.MyClass, AssemblyName");
var instance =  Activator.CreateInstance(classType);

那如果這個類是泛型類,該如何實例化呢?  這里主要是要傳遞泛型參數

復制代碼
namespace ConsoleApp2
{
    public class MyGenericClass<T>
    {

    }
}
復制代碼
Type classType = Type.GetType("ConsoleApp2.MyGenericClass`1, AssemblyName");
Type constructedType = classType.MakeGenericType(typeof(T));
var instance = Activator.CreateInstance(constructedType);

 


免責聲明!

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



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