我读了这个问题的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.");
});

其他回答

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

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

你可以试试这个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

你可以试试这个

public IEnumerable<string> Get()
 {
     return new string[] { "value1", "value2" };
 }

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

(视频中不完整的例子)

如果你的意思是返回多个值,你可以返回一个包含你想返回的值的类/结构,或者在参数上使用"out"关键字,如下所示:

public void Foo(int input, out int output1, out string output2, out string errors) {
    // set out parameters inside function
}