如何从单个方法返回两个值? [英] How do you return two values from a single method?

查看:151
本文介绍了如何从单个方法返回两个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您需要通过一种方法返回两件事时,最好的方法是什么?

When your in a situation where you need to return two things in a single method, what is the best approach?

我了解一种方法只能做一件事的理念,但是说您有一个运行数据库选择的方法,并且需要拉两列.我假设您只想遍历数据库结果集一次,但是想返回两列数据.

I understand the philosophy that a method should do one thing only, but say you have a method that runs a database select and you need to pull two columns. I'm assuming you only want to traverse through the database result set once, but you want to return two columns worth of data.

我提供的选项:

  1. 使用全局变量来保存收益. 我亲自尝试着尽量避免使用全局变量.
  2. 传入两个空变量作为参数,然后在方法内部分配变量,这现在是一个空值. 我不喜欢有副作用的方法的想法. /em>
  3. 返回包含两个变量的集合. 这会导致代码混乱.
  4. 构建一个容器类来容纳双倍收益. 这比包含其他集合的集合更具自我说明性,但似乎仅为该类创建一个类可能会造成混淆退货的目的.
  1. Use global variables to hold returns. I personally try and avoid globals where I can.
  2. Pass in two empty variables as parameters then assign the variables inside the method, which now is a void. I don't like the idea of methods that have a side effects.
  3. Return a collection that contains two variables. This can lead to confusing code.
  4. Build a container class to hold the double return. This is more self-documenting then a collection containing other collections, but it seems like it might be confusing to create a class just for the purpose of a return.

推荐答案

这并非完全与语言无关:在Lisp中,您实际上可以从函数中返回任意数量的值,包括(但不限于)无,一个,两个...

This is not entirely language-agnostic: in Lisp, you can actually return any number of values from a function, including (but not limited to) none, one, two, ...

(defun returns-two-values ()
  (values 1 2))

Scheme和Dylan也是如此.在Python中,我实际上会使用包含2个值的元组,例如

The same thing holds for Scheme and Dylan. In Python, I would actually use a tuple containing 2 values like

def returns_two_values():
   return (1, 2)

正如其他人指出的那样,您可以使用C#中的out参数返回多个值.在C ++中,您将使用引用.

As others have pointed out, you can return multiple values using the out parameters in C#. In C++, you would use references.

void 
returns_two_values(int& v1, int& v2)
{
    v1 = 1; v2 = 2;
}

在C语言中,您的方法将使用指向函数应存储结果值的位置的指针.

In C, your method would take pointers to locations, where your function should store the result values.

void 
returns_two_values(int* v1, int* v2)
{
    *v1 = 1; *v2 = 2;
}

对于Java,我通常使用专用类或相当通用的小助手(当前,我的私有公共"库中有两个:Pair<F,S>Triple<F,S,T>,它们都不过是简单的不可变容器) 2个或3个值)

For Java, I usually use either a dedicated class, or a pretty generic little helper (currently, there are two in my private "commons" library: Pair<F,S> and Triple<F,S,T>, both nothing more than simple immutable containers for 2 resp. 3 values)

这篇关于如何从单个方法返回两个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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