[英]KeyValuePair naming by ValueTuple in C# 7
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;
}
解构需要在类型本身上定义的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}");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.