13

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;
}
4

1 回答 1

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}");
    }
}
于 2017-04-07T16:11:10.277 回答