gpt4 book ai didi

c#-4.0 - C# 显式转换 - 从 KeyValuerPair 的集合到 Dictionary

转载 作者:行者123 更新时间:2023-12-04 01:15:36 30 4
gpt4 key购买 nike

我有一个 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()



作为背景知识,您始终可以从任何接口(interface)类型转换为非密封类(“目标”),即使该类型未实现该接口(interface),因为从“目标”派生的另一个类可能实现界面。

从 C# 5 规范的第 6.2.4 节:

The explicit reference conversions are:

  • ...
  • From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T.
  • ...


( 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com