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

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


当前回答

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

class div
{
    public int remainder;

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

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

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

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

其他回答

接受委托的方法可以向调用者提供多个值。这句话借鉴了我的答案,也引用了哈达斯公认的答案。

delegate void ValuesDelegate(int upVotes, int comments);
void GetMultipleValues(ValuesDelegate callback)
{
    callback(1, 2);
}

调用方提供lambda(或命名函数),智能感知通过从委托复制变量名来帮助实现。

GetMultipleValues((upVotes, comments) =>
{
     Console.WriteLine($"This post has {upVotes} Up Votes and {comments} Comments.");
});

你可以使用动态对象。我认为它比Tuple有更好的可读性。

static void Main(string[] args){
    var obj = GetMultipleValues();
    Console.WriteLine(obj.Id);
    Console.WriteLine(obj.Name);
}

private static dynamic GetMultipleValues() {
    dynamic temp = new System.Dynamic.ExpandoObject();
    temp.Id = 123;
    temp.Name = "Lorem Ipsum";
    return temp;
}
<--Return more statements like this you can --> 

public (int,string,etc) Sample( int a, int b)  
{
    //your code;
    return (a,b);  
}

你可以收到类似的代码

(c,d,etc) = Sample( 1,2);

我希望它能奏效。

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

(视频中不完整的例子)

不,在c#中(对于低于c# 7的版本),你不能从一个函数返回多个值,至少不能像在Python中那样。

然而,也有一些选择:

您可以返回一个object类型的数组,其中包含您想要的多个值。

private object[] DoSomething()
{
    return new [] { 'value1', 'value2', 3 };
}

你可以使用out参数。

private string DoSomething(out string outparam1, out int outparam2)
{
    outparam1 = 'value2';
    outparam2 = 3;
    return 'value1';
}