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

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


当前回答

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

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

例如:

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

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

其他回答

你不能在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; }
}

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

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

一些答案建议使用out参数,但我建议 不使用这个,因为它们不与异步方法一起工作。看到 这是更多的信息。

其他的答案是使用Tuple,我也会推荐它,但是使用c# 7.0中引入的新特性。

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

更多信息可以在这里找到。

您还可以使用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# 7及以上版本中,可以看到这个答案。

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

例如:

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

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