out,ref,params参数


out参数:

如果在一个方法中,返回多个相同类型的值时,可以考虑返回一个数组。

但是返回多个类型的值时,就需要用到out参数。

out参数就侧重于在一个方法中返回多个类型的值。

 1 static void Main(string[] args)
 2         {
 3             Console.WriteLine("请输入用户名");
 4             string name = Console.ReadLine();
 5             Console.WriteLine("请输入密码");
 6             string cypher = Console.ReadLine();
 7             string response;
 8             bool b=GetMaxMinSumAvg(name, cypher, out response);
 9             Console.WriteLine("登录结果{0}\t", b);
10             Console.WriteLine("登录信息{0}\t",response);
11             Console.ReadKey();
12 
13         }
14         /// 
15         /// 判断登录是否成功
16         /// 
17         /// 用户名
18         /// 密码
19         /// 多余返回的登录信息
20         /// 登录结果
21         public static bool GetMaxMinSumAvg(string name,string cypher,out string response)
22         {
23             if (name == "admin" && cypher == "88888")
24             {
25                 response = "登陆成功";
26                 return true;
27             }
28             else if (name == "admin")
29             {
30                 response = "密码错误";
31                 return false;
32             }
33             else if (cypher == "88888")
34             {
35                 response = "用户名错误";
36                 return false;
37             }
38             else
39             {
40                 response = "用户名密码全错";
41                 return false;
42             }
43         }

ref参数:

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

ref要求必须在方法外进行赋值,而方法内不需要赋值

 1 static void Main(string[] args)
 2         {
 3             int n1 = 10;
 4             int n2 = 20;
 5             Exchange(ref n1, ref n2);
 6             Console.WriteLine(n1);
 7             Console.WriteLine(n2);
 8             Console.ReadKey();
 9         }
10         public static void Exchange(ref int n1,ref int n2)
11         {
12             int temp = n1;
13             n1 = n2;
14             n2 = temp;
15         }

params可变参数:

将实参列表中跟可变参数数组类型一致的元素都当做数组的元素去处理。

params参数必须是参数列表中最后一个参数

 1 static void Main(string[] args)
 2         {
 3             int max=GetMax(1, 2, 39, 4, 45, 6, 7, 85, -9);//使用params参数后,可将实参列表中元素当做数组元素处理
 4             Console.WriteLine(max);
 5             Console.ReadKey();
 6         }
 7         /// 
 8         /// 求可变数组的最大值
 9         /// 
10         /// 需要比较的数组
11         /// 返回最大值
12         public static int GetMax(params int[] num)
13         {
14             int max = num[0];
15             for (int i = 0; i < num.Length; i++)
16             {
17                 if (num[i] > max)
18                 {
19                     max = num[i];
20                 }
21                 
22             }
23             return max;
24         }