【发布时间】:2011-08-03 22:23:11
【问题描述】:
我有:
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]]'.
我错过了什么? (嵌套泛型类型/属性的问题?)
【问题讨论】:
-
你不能把原来的内部字典类型改成
IDictionary<>吗?这将简化事情,通常这不需要对填充字典的代码进行大的更改。 -
@digEmAll:根据埃里克的回答,这只是解决了问题,并没有解决问题。
-
不,我在问你为什么不这样做:
var someConcreteInstance = new Dictionary<string, IDictionary<string, bool>>();而不是你原来的行?这可以解决问题(你甚至不需要演员表),但当然你可能有一些理由离开你的原始代码......
标签: c# generics dictionary casting nested