返回两个值,元组与“输出"与“结构" [英] Returning two values, Tuple vs 'out' vs 'struct'

查看:69
本文介绍了返回两个值,元组与“输出"与“结构"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个返回两个值的函数.我们可以这样写:

Consider a function which returns two values. We can write:

// Using out:
string MyFunction(string input, out int count)

// Using Tuple class:
Tuple<string, int> MyFunction(string input)

// Using struct:
MyStruct MyFunction(string input)

哪种是最佳实践,为什么?

Which one is best practice and why?

推荐答案

它们每个都有各自的优缺点.

They each have their pros and cons.

Out参数既快速又便宜,但是需要您传入一个变量,并且要依赖突变.在LINQ上正确使用out参数几乎是不可能的.

Out parameters are fast and cheap but require that you pass in a variable, and rely upon mutation. It is almost impossible to correctly use an out parameter with LINQ.

故障堆会增加垃圾收集压力,并且无法自我记录."Item1"不是很具描述性.

Tuples make garbage collection pressure and are un-self-documenting. "Item1" is not very descriptive.

如果自定义结构很大,则复制起来可能会很慢,但如果它们很小,则可以自我记录,并且效率很高.但是,定义一堆用于琐碎用途的自定义结构也很麻烦.

Custom structs can be slow to copy if they are large, but are self-documenting and are efficient if they are small. However it is also a pain to define a whole bunch of custom structs for trivial uses.

在其他所有条件相同的情况下,我倾向于定制结构解决方案.更好的方法是制作一个仅返回一个值的函数.为什么首先要返回两个值?

I would be inclined to the custom struct solution all other things being equal. Even better though is to make a function that only returns one value. Why are you returning two values in the first place?

更新:请注意,在撰写本文后六年,C#7中的元组是值类型,因此不太可能产生收集压力.

UPDATE: Note that tuples in C# 7, which shipped six years after this article was written, are value types and hence less likely to create collection pressure.

这篇关于返回两个值,元组与“输出"与“结构"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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