【问题标题】:How to TypeCast Dictionary of GenericType如何对 GenericType 的字典进行类型转换
【发布时间】:2018-08-29 09:41:11
【问题描述】:

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

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

现在我想把它输入:-

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

有什么办法吗?

【问题讨论】:

  • 你能在上下文中展示一个更完整的例子来说明你正在尝试做什么吗?
  • 如果它 Dictionary&lt;SomeClass, KeyValuePair&lt;int, bool&gt;&gt;,那么您可以像进行任何其他演员一样投射它。
  • 不幸的是,你不能简单地投射这个:error CS0030: Cannot convert type 'System.Collections.Generic.Dictionary&lt;SomeClassB, System.Collections.Generic. KeyValuePair&lt;int, bool&gt;&gt;' to 'System.Collections.Generic.Dictionary&lt;SomeClass, System.Collections.Generic.KeyValuePair&lt;i nt, bool&gt;&gt;'
  • 为什么要这样做?你在一个泛型类中,为什么它必须知道 SomeClass 的类型呢?
  • 泛型成员的意义在于它适用于每一种类型,而不仅仅是特定的类型。因此,如果您只有以SomeClass-elements 作为键的字典,为什么不使用Dictionary&lt;SomeClass, ...&gt;?请提供一个更有意义的示例来说明您想要实现的目标,最好以Minimal, Complete, and Verifiable example 的形式

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


【解决方案1】:

我确定有一种方法可以以不同的方式进行转换,但我首先想到的是使用 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);

【讨论】:

  • 不区分大小写?我没有看到任何涉及的字符串。你什么意思?
  • 如果使用自定义相等比较器,这可能会出现问题 - docs.microsoft.com/en-us/dotnet/api/…(因为 ToDictionary 会丢失)。
  • 是的,它不是同一个字典。但在他使用的构造函数中,并没有提示传递了 IEqualityComparer。所以它应该工作得很好。
  • 他还可以使用 ToDictionary 方法的另一个重载并传递相同的相等比较器:msdn.microsoft.com/en-us/library/bb548554(v=vs.110).aspx
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 2018-08-17
  • 2021-08-29
  • 2012-03-01
相关资源
最近更新 更多