我读了这个问题的c++版本,但并没有真正理解它。

有人能解释清楚,如果它可以在c#中完成,以及如何?


当前回答

现在c# 7已经发布了,您可以使用新包含的元组语法

(string, string, string) LookupName(long id) // tuple return type
{
    ... // retrieve first, middle and last from data storage
    return (first, middle, last); // tuple literal
}

然后可以这样使用:

var names = LookupName(id);
WriteLine($"found {names.Item1} {names.Item3}.");

您还可以为元素提供名称(因此它们不是“Item1”、“Item2”等)。你可以通过在签名或返回方法中添加一个名字来实现:

(string first, string middle, string last) LookupName(long id) // tuple elements have names

or

return (first: first, middle: middle, last: last); // named tuple elements in a literal

它们也可以被解构,这是一个非常好的新功能:

(string first, string middle, string last) = LookupName(id1); // deconstructing declaration

查看这个链接,看看更多的例子可以做什么:)

其他回答

你不能在c#中这样做。你能做的就是有一个out形参或者返回你自己的类(或者结构,如果你想让它是不可变的)。

Using out parameter
public int GetDay(DateTime date, out string name)
{
  // ...
}
Using custom class (or struct)
public DayOfWeek GetDay(DateTime date)
{
  // ...
}

public class DayOfWeek
{
  public int Day { get; set; }
  public string Name { get; set; }
}

类、结构、集合和数组可以包含多个值。也可以在函数中设置输出和引用参数。在动态和函数式语言中可以通过元组返回多个值,但在c#中不可以。

c#的未来版本将包括命名元组。 看看channel9的演示 https://channel9.msdn.com/Events/Build/2016/B889

跳到13:00讲元组的内容。这将允许如下内容:

(int sum, int count) Tally(IEnumerable<int> list)
{
// calculate stuff here
return (0,0)
}

int resultsum = Tally(numbers).sum

(视频中不完整的例子)

在面向对象的方式中使用一个这样的类:

class div
{
    public int remainder;

    public int quotient(int dividend, int divisor)
    {
        remainder = ...;
        return ...;
    }
}

函数成员返回大多数调用者主要感兴趣的商。此外,它将余数存储为数据成员,之后调用者可以很容易地访问它。

通过这种方式,您可以有许多额外的“返回值”,这在实现数据库或网络调用时非常有用,在这些调用中可能需要大量的错误消息,但仅在发生错误时才需要。

我也在OP提到的c++问题中输入了这个解决方案。

在c# 7及以上版本中,可以看到这个答案。

在以前的版本中,你可以使用。net 4.0+的元组:

例如:

public Tuple<int, int> GetMultipleValue()
{
     return Tuple.Create(1,2);
}

有两个值的元组有Item1和Item2作为属性。