VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • C# 方法的out、ref、params参数(2)

执行代码输出结果,如图所示:

总结:

如果一个方法中,返回多个相同类型的值时候,我们可以考虑返回一个数组。但是返回多个不同类型的值时候,返回数组就不行,那么这个时候,我们可以考虑用out参数。

out参数就侧重于一个方法可以返回多个不同类型的值。

 

二、ref参数的实例

【实例】使用方法来交换两个int类型的变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Program
   {
       static void Main(string[] args)
       {
           //使用方法来交换两个int类型的变量
           int n1 = 10;
           int n2 = 20;
           Test(ref n1, ref n2);
           Console.WriteLine("两个值互相交换后n1为{0},n2为:{1}",n1,n2);
           Console.ReadKey();
       }
       public static void  Test(ref int n1,ref int n2)
       {
           int temp = n1;
           n1 = n2;
           n2 = temp;
       }
   }

执行代码输出结果,如图所示:

总结:

ref参数能够将一个变量带入一个方法中进行改变,改变完成后,再将改变后的值带出方法。

 ref参数要求在方法外必须要赋值,而方法内可以不赋值。

 

三、params可变参数

【实例】求任意长度数组的和 整数类型的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Program
   {
       static void Main(string[] args)
       {
           //求任意长度数组的和 整数类型的
           int[] nums = { 1, 2, 3, 4, 5, 6 };
           int sum = GetSum(8,9);
           Console.WriteLine(sum);
           Console.ReadKey();
       }
       public static int GetSum(params int[] nums)
       {
           int sum = 0;
           for (int i = 0; i < nums.Length; i++)
           {
               sum += nums[i];
           }
           return sum;
       }
   } 

相关教程