我有一個通用的字典:鑄造包含通用詞典
var someConcreteInstance = new Dictionary<string, Dictionary<string, bool>>();
,我希望將其轉換爲一個接口的版本,即:
someInterfaceInstance = (IDictionary<string, IDictionary<string, bool>>)someConcreteInstance;
「someInterfaceInstance」是公共財產:
IDictionary<string, IDictionary<string, bool>> someInterfaceInstance { get; set; }
這種編譯正確,但會引發運行時轉換錯誤。
Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.String,System.Boolean]]' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Collections.Generic.IDictionary`2[System.String,System.Boolean]]'.
我在想什麼? (嵌套泛型/ Property的問題)
難道你不能改變你的原始內部字典類型爲'IDictionary <>'?這將簡化一些事情,通常這不需要填充字典的代碼中的大的改變。 – digEmAll 2011-04-12 14:20:09
@digEmAll:根據Eric的回答,這只是簡單地解決了問題,但並沒有解決問題。 – nicodemus13 2011-04-12 15:00:19
不,我問你爲什麼不這樣做:'var someConcreteInstance = new Dictionary>();'而不是原始行?這將解決問題(你甚至不需要演員),但當然你可以有一些理由讓你的原代碼... –
digEmAll
2011-04-12 15:07:15