KeyValuePair<>中的Deconstruct方法的目的是什么?结构? [英] What is the purpose of Deconstruct method in KeyValuePair<> struct?

查看:28
本文介绍了KeyValuePair<>中的Deconstruct方法的目的是什么?结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

签名如下:

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

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

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

推荐答案

解构是 C# 7 中主要为值元组引入的一项功能,让您可以在单个操作中解包元组中的所有项目".语法已被通用化以允许它也用于其他类型.通过定义 Deconstruct 方法,您可以使用简洁的解构语法将内部值分配给各个变量:

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;

您甚至可以通过使用 out 参数和 void 返回类型定义这样的 Deconstruct 方法,将解构应用于您自己的用户定义类型,就像你的例子一样.请参阅解构用户定义的类型.

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.

编辑:虽然 .NET Framework 和 .NET Core 都支持 C# 7 解构语法,但 KeyValuePair.Deconstruct 方法目前仅在 .NET 中支持核心 2.0 及更高版本.请参阅上一个链接中的适用于"部分.

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.

这篇关于KeyValuePair&lt;&gt;中的Deconstruct方法的目的是什么?结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆