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

被刻印的时光 ゝ 提交于 2019-12-24 02:55:26

问题


I was looking at System.Collections.Generic.KeyValuePair<TKey, TValue> struct in System.Runtime, Version=4.2.1.0 and this method took my attention.

Here's the signature:

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

Does it contain any logic besides simply forwarding Key and Value properties? Why would anyone ever prefer it over property getters?


回答1:


Deconstruction is a feature that was introduced mainly for value tuples in C# 7, letting you "unpackage all the items in a tuple in a single operation". The syntax has been generalized to allow it to be used for other types too. By defining the Deconstruct method, you can then use concise deconstruction syntax to assign the internal values to individual variables:

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

You can even apply deconstruction to your own user-defined types by defining such a Deconstruct method with out parameters and a void return type, like in your example. See Deconstructing user-defined types.

Edit: Whilst the C# 7 deconstruction syntax is supported in both .NET Framework and .NET Core, the KeyValuePair<TKey,TValue>.Deconstruct method is currently only supported in .NET Core 2.0 and later. Refer to the "Applies to" section in the previous link.




回答2:


Deconstuction is used to allow pattern matching (FP concepts available in Scala) in C#,This will yield key & values separatly. Also the same can use switch expression too.

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


来源:https://stackoverflow.com/questions/51809890/what-is-the-purpose-of-deconstruct-method-in-keyvaluepair-struct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!