【封装成一个类返回】
【类、字典、泛型列表都是引用类型的,因此,在某个方法中对他们进行操作,会有全局影响的效果】
class MainClass
{
public class Result//字段的声明
{
public int add { get; set; }
public int sub { get; set; }
public int mul { get; set; }
}
static Result Calculate(int a , int b)
{
Result result = new Result();
result.add = a + b;
result.sub = a - b;
result.mul = a * b;
return result;//返回一个类
}
static void Main(string[] args)
{
Result result = Calculate(5, 3);//用result接收这个类,用于后续调用
Console.WriteLine(result.add);
Console.WriteLine(result.sub);
Console.WriteLine(result.mul);
}
}
【out关键字】
class MainClass
{
static void Calculate(int a , int b , out int add ,out int sub,out int mul)
{
add = a + b;
sub = a - b;
mul = a * b;
}
static void Main(string[] args)
{
Calculate(5, 3, out int add, out int sub, out int mul);
Console.WriteLine(add); Console.WriteLine(sub); Console.WriteLine(mul);
}
}
【以元组返回】
class MainClass
{
static (int,int,int) Calculate(int a, int b)
{
int add, sub, mul;
add = a + b;
sub = a - b;
mul = a * b;
return (add, sub, mul);
}
static void Main(string[] args)
{
var result = Calculate(5, 3);
Console.WriteLine(result);//(8,2,15)
Console.WriteLine(result.Item1);//8
}
}