KeyValuePair<> 结构中 Deconstruct 方法的目的是什么?

What is the purpose of Deconstruct method in KeyValuePair<> struct?

我正在查看 System.Runtime, Version=4.2.1.0 中的 System.Collections.Generic.KeyValuePair<TKey, TValue> 结构,这个方法引起了我的注意。

签名如下:

public void Deconstruct(out TKey key, out TValue value);

除了简单转发KeyValue属性外,是否包含任何逻辑?为什么有人会比 属性 吸气剂更喜欢它?

解构是 C# 7 中主要为值元组引入的一个特性,让你 "unpackage all the items in a tuple in a single operation"。语法已被通用化以允许它也用于其他类型。通过定义 Deconstruct 方法,您可以使用简洁的解构语法将内部值分配给各个变量:

var kvp = new KeyValuePair<int, string>(10, "John");
var (id, name) = kvp;

您甚至可以通过使用 out 参数和 void return 类型定义这样的 Deconstruct 方法,将解构应用于您自己的用户定义类型,例如你的例子。参见 Deconstructing user-defined types

编辑:虽然 .NET Framework 和 .NET Core 都支持 C# 7 解构语法,但目前仅 .NET Core 支持 KeyValuePair<TKey,TValue>.Deconstruct 方法2.0 及更高版本。参考前面link中的"Applies to"部分。

解构用于允许在 C# 中进行模式匹配(Scala 中可用的 FP 概念),这将分别生成键和值。同样也可以使用switch表达式。

KeyValuePairTest(new KeyValuePair<string, string>("Hello", "World"));
KeyValuePairTest(new KeyValuePair<int, int>(5,7));

private static void KeyValuePairTest<TKey, TValue>(KeyValuePair<TKey,TValue> keyValuePair)
{
    var (k, v) = keyValuePair;
    Console.WriteLine($"Key {k}, value is {v}");

    switch (keyValuePair)
    {
        case KeyValuePair<string, string> t:
            Console.WriteLine(t.Key + " " + t.Value);break;
        case KeyValuePair<int, int> t:
            Console.WriteLine(t.Key + t.Value); break;
    }
}