C#7.0中的新功能(在VS 2017中)是否可以将元组字段名称转换为KeyValuePairs?
让我们假设我有这个:
class Entry
{
public string SomeProperty { get; set; }
}
var allEntries = new Dictionary<int, List<Entry>>();
// adding some keys with some lists of Entry
做一些像这样的事情会很好:
foreach ((int collectionId, List<Entry> entries) in allEntries)
我已将System.ValueTuple
添加到项目中。
能够像这样写它会比这种传统风格好得多:
foreach (var kvp in allEntries)
{
int collectionId = kvp.Key;
List<Entry> entries = kvp.Value;
}
答案 0 :(得分:20)
解构需要在类型本身上定义Deconstruct
方法,或者作为扩展方法。 KeyValuePaire<K,V>
本身没有Deconstruct
方法,因此您需要定义扩展方法:
static class MyExtensions
{
public static void Deconstruct<K,V>(this KeyValuePair<K,V> kvp, out K key, out V value)
{
key=kvp.Key;
value=kvp.Value;
}
}
这允许你写:
var allEntries = new Dictionary<int, List<Entry>>();
foreach(var (key, entries) in allEntries)
{
...
}
例如:
var allEntries = new Dictionary<int, List<Entry>>{
[5]=new List<Entry>{
new Entry{SomeProperty="sdf"},
new Entry{SomeProperty="sdasdf"}
},
[11]=new List<Entry>{
new Entry{SomeProperty="sdfasd"},
new Entry{SomeProperty="sdasdfasdf"}
}, };
foreach(var (key, entries) in allEntries)
{
Console.WriteLine(key);
foreach(var entry in entries)
{
Console.WriteLine($"\t{entry.SomeProperty}");
}
}