在C#7中是否可以在字典中的foreach循环中使用解构?像这样的东西:
var dic = new Dictionary<string, int>{ ["Bob"] = 32, ["Alice"] = 17 };
foreach (var (name, age) in dic)
{
Console.WriteLine($"{name} is {age} years old.");
}
Run Code Online (Sandbox Code Playgroud)
它似乎不适用于Visual Studio 2017 RC4和.NET Framework 4.6.2:
错误CS1061:'KeyValuePair'不包含'Deconstruct'的定义,并且没有扩展方法'Deconstruct'可以找到接受类型'KeyValuePair'的第一个参数(你是否缺少using指令或汇编引用?)
gar*_*ese 38
首先,您必须为以下内容添加扩展方法KeyValuePair:
public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple, out T1 key, out T2 value)
{
key = tuple.Key;
value = tuple.Value;
}
Run Code Online (Sandbox Code Playgroud)
然后你会得到一个不同的错误:
错误CS8179:未定义或导入预定义类型'System.ValueTuple`2'
根据这个答案,你必须安装NuGet包System.ValueTuple.
然后它应该编译.但是,Visual Studio 2017 RC4会说它无法解析符号名称name和age.他们应该希望在未来的更新中解决这个问题.
Rya*_*ndy 24
如果您不喜欢编写该Deconstruct方法,特别是如果您只需要在一个地方使用它,那么这里是如何使用LINQ作为单行程序:
使用原始字典:
var dic = new Dictionary<string, int>{ ["Bob"] = 32, ["Alice"] = 17 };
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
foreach (var (name, age) in dic.Select(x => (x.Key, x.Value)))
{
Console.WriteLine($"{name} is {age} years old.");
}
Run Code Online (Sandbox Code Playgroud)
hil*_*lin 16
Deconstruct不幸的KeyValuePair<TKey,TValue>是,.NET Core .NET Core 2.0中实现了该功能,但.NET Framework(最高4.8个预览版)中没有实现。