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

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


当前回答

作为一种替代方法,您可以将方法设置为void并且不返回任何内容。相反,创建一个带有参数的公共类,并在方法中设置它们。

public class FooBar()
{
    public string foo { get; set; }
    public int bar { get; set; }
}

然后试试这个方法

public void MyMethod(Foo foo, Bar bar)
{
    FooBar fooBar = new FooBar();
    fooBar.foo = "some string";
    fooBar.bar = 1;
}

其他回答

<--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);

我希望它能奏效。

要么返回类实例,要么使用out参数。这里有一个out参数的例子:

void mymethod(out int param1, out int param2)
{
    param1 = 10;
    param2 = 20;
}

这样叫它:

int i, j;
mymethod(out i, out j);
// i will be 20 and j will be 10

你可以试试这个

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

在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自己的库中使用它,而不是在您自己的函数中。

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

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