簡體   English   中英

在數據結構中使用通過反射獲得的類型?

[英]Using a type obtained through reflection in a data structure?

我有一個.NET 4.6中存在的FutureClass類,但是我希望能夠在使用.NET 4.0構建的舊代碼庫中使用它。 我可以獲取並調用FutureClass對象,但是我想將它們存儲在Dictionary<string, FutureClass>

我嘗試了以下方法:

Dictionary<string, FutureClass> dict = new Dictionary<string, FutureClass>(); // didn't expect it to work

Type futureClassType = [...] //dynamically load the type from the assembly compiled with .NET 4.6
Dictionary<string, futureClassType> dict = new Dictionary<string, futureClassType>(); // held some promise, I thought

有辦法做我想做的事嗎? 謝謝!

就靜態鍵入字典變量而言,我認為您只能使用以下兩個選項之一:使用Dictionary<string, object>Dictionary<string, dynamic>

否則,您可以執行以下操作:

Type futureClassType = ...;
var dictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string), futureClassType);
var dictionary = Activator.CreateInstance(dictionaryType);

但是在這里,結果dictionary變量是對象類型。 您可以將其IDictionary轉換為非通用IDictionaryICollectionIEnumerable ,但不能將其強制轉換為上述任意一種的通用形式。

在運行時加載類型有一些嚴重的障礙,就像您剛遇到的那樣。 您不能在編譯時表達式中使用類型,就像將其用作通用類型參數一樣。

唯一的選擇是將類復制到自己的代碼庫中,這應該不太困難,因為.NET框架現已正式開源。 您可能遇到的唯一麻煩是該類具有許多.NET> = 4.5依賴關系,可能是遞歸的。

暫無
暫無

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

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