如何键入GenericType的快速字典

时间:2018-08-29 09:41:11

标签: c# casting type-conversion explicit-conversion

我有一个字典对象,如:-

var gridContent = new Dictionary<T, KeyValuePair<int, bool>>();

现在我要将此内容键入:-

Dictionary<SomeClass, KeyValuePair<int, bool>>();

有什么办法吗?

1 个答案:

答案 0 :(得分:0)

我敢肯定有一种方法可以用不同的方式进行转换,但是我想到的第一件事就是使用Linq进行转换:

PS> scriptcs
scriptcs (ctrl-c to exit or :help for help)

> public class SomeClass {}
> public class SomeClassB : SomeClass {}
> public class Test<T> where T: SomeClass
* {
*     public Dictionary<T, KeyValuePair<int, bool>> gridContent = new Dictionary<T, KeyValuePair<int, bool>>();
* }
>
> var testInstance = new Test<SomeClassB>();
> // casting error
> // var testGridContent = (Dictionary<SomeClass, KeyValuePair<int, bool>>)testInstance.gridContent;
>
> var testGridContent = testInstance.gridContent.ToDictionary(kvp=>(SomeClass)kvp.Key, kvp=>kvp.Value);