首頁 >後端開發 >C++ >我可以將實例化system.type作為c#中的通用類型參數傳遞嗎?

我可以將實例化system.type作為c#中的通用類型參數傳遞嗎?

DDD
DDD原創
2025-02-01 12:16:11236瀏覽

Can I Pass an Instantiated System.Type as a Generic Type Parameter in C#?

> >將實例化system.type作為通用類>

>的類型參數,該問題圍繞著構建通用類的可行性的問題實例化類型實例。具體而言,可以創建MyGenericClass< mytype>在哪裡動態確定myType?

>直接方法導致編譯器錯誤“找不到類型或名稱空間'mytype'。為了克服此限制,反射提供了解決方案。

使用反射,可以動態創建與通用類的類型參數兼容的類型。以下是一個示例:
public class Generic<T>
{
    public Generic()
    {
        Console.WriteLine("T={0}", typeof(T));
    }
}

class Test
{
    static void Main()
    {
        string typeName = "System.String";
        Type typeArgument = Type.GetType(typeName);

        Type genericClass = typeof(Generic<>);
        // MakeGenericType is badly named
        Type constructedClass = genericClass.MakeGenericType(typeArgument);

        object created = Activator.CreateInstance(constructedClass);
    }
}

請注意,該示例使用單個類型參數,但支持多個參數。要省略具有多個參數的通用類的類型參數,如下示例所示,包括佔位符中的逗號:
Type genericClass = typeof(IReadOnlyDictionary<>, <>);
Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);

以上是我可以將實例化system.type作為c#中的通用類型參數傳遞嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn