簡體   English   中英

從Type變量中獲取實際類型

[英]Get the actual type from a Type variable

我試圖從Type變量中獲取一個類型。 例如:

Type t = typeof(String);
var result = SomeGenericMethod<t>();

第二行發生錯誤,因為t不是type ,它是變量。 有什么辦法讓它成為一種類型?

要基於Type創建泛型的實例,可以使用反射來獲取要使用的類型的泛型實例,然后使用Activator創建該實例:

Type t = typeof (string); //the type within our generic

//the type of the generic, without type arguments
Type listType = typeof (List<>); 

//the type of the generic with the type arguments added
Type generictype = listType.MakeGenericType(t); 

//creates an instance of the generic with the type arguments.
var x = Activator.CreateInstance(generictype);

請注意,此處的x將是一個object 要調用它上面的函數,例如.Sort() ,你必須使它成為dynamic函數。

請注意 ,此代碼難以閱讀,編寫,維護,理由,理解或喜愛。 如果您有任何替代方案需要使用這種結構,請徹底探索這些結構。

編輯 :您還可以轉換從Activator接收的對象,例如(IList)Activator.CreateInstance(genericType) 這將為您提供一些功能,而無需訴諸動態。

不,您無法在編譯時知道Type對象的值,這是您需要執行的操作才能將Type對象用作實際類型。 無論您正在做什么,需要使用該Type將需要動態地執行此操作,並且不需要在編譯時具有已知類型。

使用反射的丑陋的解決方法:

具有泛型方法的類

public class Dummy {
        public string WhatEver<T>() {
            return "Hello";
        }    
    }

用法

 var d = new Dummy();
 Type t = typeof(string);
 var result = typeof(Dummy).GetMethod("WhatEver").MakeGenericMethod(t).Invoke(d, null);

在類實例化上,請參閱Max的解決方案

暫無
暫無

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

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