簡體   English   中英

從動態類型創建泛型類的實例

[英]Create instance of generic class from a dynamic type

是否可以創建動態派生類型的泛型類的實例。

Class GenericClass<T> {

}

Main()
{
    string inputtype = "classname, assemblyname";

    Type type = Type.GetType(inputtype);

    dynamic instance = Activator.CreateInstance(type);

    // Want to create a object of GenericClass<T> but I get compiletime errors.
    // Is it possible to do like below?

    GenericClass<instance> = new GenericClass<instance>();
}

您可以像這樣使用反射:

object genericInstance = Activator.CreateInstance(typeof(GenericClass<>).MakeGenericType(type));

但是你必須強制轉換它才能使用它,所以它不是類型安全的。

是的,您可以在運行時實例化一個泛型類型,知道它期望的泛型類型參數。 你能用它做任何有用的事情嗎? 那要看。

這是一個例子。 請注意,我有一個(非通用)接口,它為我提供了一種可以使用的行為:

public class Program
{
    public static void Main(string[] args)
    {

        var genericType = typeof(int); // You could have a string and Type.GetType here
        var genericClassType = typeof(GenericClass<>).MakeGenericType(genericType);
        var instance = (ICanTellYouMyType)Activator.CreateInstance(genericClassType);
        Console.WriteLine(instance.WhatsMyGenericType()); 
        // Output is "Int32"

    }
}

public interface ICanTellYouMyType
{
    string WhatsMyGenericType();
}

public class GenericClass<T> : ICanTellYouMyType
{
    public string WhatsMyGenericType()
    {
        return typeof(T).Name;
    }
}

實例: https : //rextester.com/XJHFM53278

其他答案實際上並沒有回答您的問題,即:

我可以這樣做: GenericClass<instance> = new GenericClass<instance>(); ?

不,你不能。 正如其他答案所解釋的那樣,您可以通過反射創建一個類型僅在運行時已知的通用對象,但您不能利用您在編譯時剛剛創建的對象的任何類型的類型信息。

¿你怎么能,如果它只在運行時知道? 如果它不僅在運行時已知,那么您一開始就不會陷入困境; 您會在編譯時(在您的代碼中)指定一個可分配類型。

泛型在這里是一個紅鯡魚。 您的問題基本上是在編寫代碼時不知道對象的類型:

Type t = someMethodGivesMeATypeIDontKnowWhenWritingThisCode();

//I need to make an instance of this type.
//The only thing I know is that it needs to have a default contructor
//or it will crash
var o = Activator.CreateInstance(t);

你認為o的編譯時間是多少? 它不能是object因為編譯器不知道也不能知道對象的真實類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM