- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 KeyValuePairs 列表。我通常会使用 ToDictionary
.
但是我刚刚注意到错误消息(如下所示)与显式转换有关,这意味着我实际上可以将列表转换为 Dictionary<...>
.我怎样才能做到这一点?Cannot implicitly convert type 'System.Linq.IOrderedEnumerable<System.Collections.Generic.KeyValuePair<int,string>>' to 'System.Collections.Generic.Dictionary<int, string>'. An explicit conversion exists (are you missing a cast?)
示例代码:
Dictionary<int, string> d = new Dictionary<int, string>() {
{3, "C"},
{2, "B"},
{1, "A"},
};
var s = d.OrderBy(i => i.Value);
d = s;
最佳答案
Implies I can actually cast list to dictionary
IOrderedEnumerable<KeyValuePair<string, string>> pairs = GetPairs();
Dictionary<string, string> dictionary = (Dictionary<string, string>) pairs;
GetPairs()
返回的值是从
Dictionary<,>
派生的类这也实现了
IOrderedEnumerable<KeyValuePair<string, string>>
.在普通代码中实际上不太可能是这种情况。编译器不能阻止你尝试,但它不会很好地结束。 (特别是,如果您使用问题中的代码和标准 LINQ to Objects 执行此操作,它肯定会在执行时失败。)
ToDictionary
...虽然你也应该知道你会失去订购,所以订购它是没有意义的。
Dictionary<int, string> d = new Dictionary<int, string>() {
{3, "C"},
{2, "B"},
{1, "A"},
};
var s = d.OrderBy(i => i.Value);
d = (Dictionary<int, string>) s;
Unhandled Exception: System.InvalidCastException: Unable to cast object of type
'System.Linq.OrderedEnumerable`2[System.Collections.Generic.KeyValuePair`2[System.Int32,System.String],System.String]'
to type'System.Collections.Generic.Dictionary`2[System.Int32,System.String]'
.
at Test.Main()
The explicit reference conversions are:
- ...
- From any class-type
S
to any interface-typeT
, providedS
is not sealed and providedS
does not implementT
.- ...
S
确实实现了
T
的情况被隐式引用转换所覆盖。)
using System;
class Test
{
static void Main()
{
IFormattable x = GetObject();
}
static object GetObject()
{
return DateTime.Now.Second >= 30 ? new object() : 100;
}
}
Test.cs(7,26): error CS0266: Cannot implicitly convert type 'object' to
'System.IFormattable'. An explicit conversion exists (are you missing a cast?)
IFormattable x = (IFormattable) GetObject();
关于c#-4.0 - C# 显式转换 - 从 KeyValuerPair 的集合到 Dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24310939/
我是一名优秀的程序员,十分优秀!