我读了这个问题的c++版本,但并没有真正理解它。
有人能解释清楚,如果它可以在c#中完成,以及如何?
我读了这个问题的c++版本,但并没有真正理解它。
有人能解释清楚,如果它可以在c#中完成,以及如何?
当前回答
在c# 4中,您将能够使用元组的内置支持轻松地处理这个问题。
与此同时,我们有两种选择。
首先,可以使用ref或out参数为参数赋值,然后将这些值传递回调用例程。
这看起来像:
void myFunction(ref int setMe, out int youMustSetMe);
其次,您可以将返回值包装到结构或类中,并将它们作为该结构的成员传递回去。KeyValuePair适用于2 -超过2你需要一个自定义类或结构。
其他回答
如果你的意思是返回多个值,你可以返回一个包含你想返回的值的类/结构,或者在参数上使用"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作为属性。
在面向对象的方式中使用一个这样的类:
class div
{
public int remainder;
public int quotient(int dividend, int divisor)
{
remainder = ...;
return ...;
}
}
函数成员返回大多数调用者主要感兴趣的商。此外,它将余数存储为数据成员,之后调用者可以很容易地访问它。
通过这种方式,您可以有许多额外的“返回值”,这在实现数据库或网络调用时非常有用,在这些调用中可能需要大量的错误消息,但仅在发生错误时才需要。
我也在OP提到的c++问题中输入了这个解决方案。