我读了这个问题的c++版本,但并没有真正理解它。
有人能解释清楚,如果它可以在c#中完成,以及如何?
我读了这个问题的c++版本,但并没有真正理解它。
有人能解释清楚,如果它可以在c#中完成,以及如何?
当前回答
你可以用三种不同的方法
1. Ref / out参数
使用参考:
static void Main(string[] args)
{
int a = 10;
int b = 20;
int add = 0;
int multiply = 0;
Add_Multiply(a, b, ref add, ref multiply);
Console.WriteLine(add);
Console.WriteLine(multiply);
}
private static void Add_Multiply(int a, int b, ref int add, ref int multiply)
{
add = a + b;
multiply = a * b;
}
使用:
static void Main(string[] args)
{
int a = 10;
int b = 20;
int add;
int multiply;
Add_Multiply(a, b, out add, out multiply);
Console.WriteLine(add);
Console.WriteLine(multiply);
}
private static void Add_Multiply(int a, int b, out int add, out int multiply)
{
add = a + b;
multiply = a * b;
}
2. 结构/类
使用结构体:
struct Result
{
public int add;
public int multiply;
}
static void Main(string[] args)
{
int a = 10;
int b = 20;
var result = Add_Multiply(a, b);
Console.WriteLine(result.add);
Console.WriteLine(result.multiply);
}
private static Result Add_Multiply(int a, int b)
{
var result = new Result
{
add = a * b,
multiply = a + b
};
return result;
}
使用类:
class Result
{
public int add;
public int multiply;
}
static void Main(string[] args)
{
int a = 10;
int b = 20;
var result = Add_Multiply(a, b);
Console.WriteLine(result.add);
Console.WriteLine(result.multiply);
}
private static Result Add_Multiply(int a, int b)
{
var result = new Result
{
add = a * b,
multiply = a + b
};
return result;
}
3.元组
Tuple类
static void Main(string[] args)
{
int a = 10;
int b = 20;
var result = Add_Multiply(a, b);
Console.WriteLine(result.Item1);
Console.WriteLine(result.Item2);
}
private static Tuple<int, int> Add_Multiply(int a, int b)
{
var tuple = new Tuple<int, int>(a + b, a * b);
return tuple;
}
c# 7元组
static void Main(string[] args)
{
int a = 10;
int b = 20;
(int a_plus_b, int a_mult_b) = Add_Multiply(a, b);
Console.WriteLine(a_plus_b);
Console.WriteLine(a_mult_b);
}
private static (int a_plus_b, int a_mult_b) Add_Multiply(int a, int b)
{
return(a + b, a * b);
}
其他回答
从这篇文章中,你可以使用上面提到的三个选项。
KeyValuePair是最快的方法。
Out是在秒。
Tuple是最慢的。
不管怎样,这取决于什么对你的情况是最好的。
接受委托的方法可以向调用者提供多个值。这句话借鉴了我的答案,也引用了哈达斯公认的答案。
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.");
});
如果你的意思是返回多个值,你可以返回一个包含你想返回的值的类/结构,或者在参数上使用"out"关键字,如下所示:
public void Foo(int input, out int output1, out string output2, out string errors) {
// set out parameters inside function
}
你可以试试这个
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
在面向对象的方式中使用一个这样的类:
class div
{
public int remainder;
public int quotient(int dividend, int divisor)
{
remainder = ...;
return ...;
}
}
函数成员返回大多数调用者主要感兴趣的商。此外,它将余数存储为数据成员,之后调用者可以很容易地访问它。
通过这种方式,您可以有许多额外的“返回值”,这在实现数据库或网络调用时非常有用,在这些调用中可能需要大量的错误消息,但仅在发生错误时才需要。
我也在OP提到的c++问题中输入了这个解决方案。