- static void Main(string[] args)
- {
-
- //声明两个变量
- int numOne = 10;
- int numTwo = 20;
- //声明平均值和总和,并调用方法
- int avg;
- int sum = GetSumAndAvg(ref numOne, ref numTwo, out avg);
- Console.WriteLine("{0},{1},{2},{3}", sum, avg, numOne, numTwo);
- Console.ReadKey();
- }
- /// <summary>
- /// ref侧重于把变量带进方法里,然后在方法里重新赋值后,再带出来,out则是可以多返回一个值
- /// </summary>
- /// <param name="numOne"></param>
- /// <param name="numTwo"></param>
- /// <param name="avg"></param>
- /// <returns></returns>
- public static int GetSumAndAvg(ref int numOne, ref int numTwo, out int avg)//如果这里不用ref交换变量不会成功
- {
- //交换变量,并计算总和还有平均值
- int numThree = numOne;
- numOne = numTwo;
- numTwo = numThree;
- int sum = numOne + numTwo;
- avg = sum / 2;
- return sum;//返回总和,用了out能多返回一个平均值avg
- }
复制代码 |