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

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


当前回答

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

class div
{
    public int remainder;

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

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

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

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

其他回答

在c# 4中,您将能够使用元组的内置支持轻松地处理这个问题。

与此同时,我们有两种选择。

首先,可以使用ref或out参数为参数赋值,然后将这些值传递回调用例程。

这看起来像:

void myFunction(ref int setMe, out int youMustSetMe);

其次,您可以将返回值包装到结构或类中,并将它们作为该结构的成员传递回去。KeyValuePair适用于2 -超过2你需要一个自定义类或结构。

不,在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';
}

现在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

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

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

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.");
});
<--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);

我希望它能奏效。