-1

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

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

现在我想把它输入:-

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

有什么办法吗?

4

1 回答 1

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);
于 2018-08-29T09:59:26.817 回答