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

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


当前回答

在c# 7中有一个新的元组语法:

static (string foo, int bar) GetTuple()
{
    return ("hello", 5);
}

你可以返回一个记录:

var result = GetTuple();
var foo = result.foo
// foo == "hello"

你也可以使用新的解构器语法:

(string foo) = GetTuple();
// foo == "hello"

但是要小心序列化,所有这些都是语法糖——在实际编译的代码中,这将是一个Tuple<string, int>(根据接受的答案),包含Item1和Item2,而不是foo和bar。这意味着序列化(或反序列化)将使用这些属性名。

因此,对于序列化,声明一个记录类并返回它。

c# 7中的另一个新特性是改进了out形参的语法。你现在可以内联声明out,这在某些情况下更适合:

if(int.TryParse("123", out int result)) {
    // Do something with result
}

但是,大多数情况下,您将在. net自己的库中使用它,而不是在您自己的函数中。

其他回答

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

public void Foo(int input, out int output1, out string output2, out string errors) {
    // set out parameters inside function
}
<--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);

我希望它能奏效。

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

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

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

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

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

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

这看起来像:

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

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