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

有人能解释清楚,如果它可以在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.");
});

其他回答

您还可以使用OperationResult

public OperationResult DoesSomething(int number1, int number2)
{
// Your Code
var returnValue1 = "return Value 1";
var returnValue2 = "return Value 2";

var operationResult = new OperationResult(returnValue1, returnValue2);
return operationResult;
}

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

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

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

这看起来像:

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

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

有许多方法;但如果你不想创建一个新的对象或结构或类似的东西,你可以在c# 7.0之后这样做:

 (string firstName, string lastName) GetName(string myParameter)
    {
        var firstName = myParameter;
        var lastName = myParameter + " something";
        return (firstName, lastName);
    }

    void DoSomethingWithNames()
    {
        var (firstName, lastName) = GetName("myname");

    }

你可以试试这个KeyValuePair

private KeyValuePair<int, int> GetNumbers()
{
  return new KeyValuePair<int, int>(1, 2);
}


var numbers = GetNumbers();

Console.WriteLine("Output : {0}, {1}",numbers.Key, numbers.Value);

输出:

输出:1,2

从这篇文章中,你可以使用上面提到的三个选项。

KeyValuePair是最快的方法。

Out是在秒。

Tuple是最慢的。

不管怎样,这取决于什么对你的情况是最好的。