gpt4 book ai didi

c# - C# 7 中 ValueTuple 的 KeyValuePair 命名

转载 作者:可可西里 更新时间:2023-11-01 08:06:07 24 4
gpt4 key购买 nike

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}");
}
}

关于c# - C# 7 中 ValueTuple 的 KeyValuePair 命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43282369/

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