C#方法学习
一、<b站C#学习>
我们在Main()函数中调用Text()函数,我们管Main()函数叫做调用者,管Text()函数叫做被调用者。
如果被调用者想要得到调用者的值
(1)传递参数
(2)使用静态变量模拟全局变量
如果调用者想要得到被调用者的值
(1)返回值
不管是形参还是实参都是在内存中开辟了空间
例1:
1 using System; 2 namespace fangfa_1 3 { 4 class Program 5 { 6 //读取输入的数字 7 //多次调用,如果输入的是数字,则返回,否则提示用户重新输入 8 //被调用者想要得到调用者的值,最简单的办法就是传参 9 //形参和实参没有直接关系,分属于不同的作用域,相同的是我这边有一个参数string类型,在调用时候也是一个string类型 10 public static int GetNumber(string s)//把s形参传进来 11 { 12 while (true) 13 { 14 try 15 { 16 int num = Convert.ToInt32(s);//注意这里写的是s,不是Console.ReadLine 17 return num;//返回int ,将void改成int 18 } 19 catch //转换失败 20 { 21 Console.WriteLine("重新输入!!!"); 22 s = Console.ReadLine();//如果没这段代码,当输入非数字时会陷入死循环 23 } 24 } 25 } 26 static void Main() 27 { 28 Console.WriteLine("请输入一个数字"); 29 string input = Console.ReadLine();//调用时传的是input实参 30 int number = GetNumber(input); 31 Console.WriteLine(number); 32 Console.ReadKey(); 33 } 34 35 } 36 }
三、方法的功能一定要单一 GetMax(int n1,int n2)
方法中最忌讳的就是出现提示用户输入的字眼
四、out ref params
1)out
如果在一个方法里面,返回多个相同类型的值的时候,可以考虑使用数组
1 using System; 2 namespace Practice 3 { 4 //案例3:计算输入数组的和:int Sum(int[] values) 5 class Program 6 { 7 public static int GetSum(int[] t1 ) 8 { 9 10 int sum = 0; 11 for (int i = 0; i < t1.Length; i++) 12 { 13 sum += t1[i]; 14 } 15 return sum; 16 } 17 static void Main() 18 { 19 int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 20 int sum = GetSum(num); 21 Console.WriteLine(sum); 22 Console.ReadKey(); 23 } 24 } 25 }
如果返回多个不同类型的值的时候,返回数组就不行了,那么这个时候可以考虑使用out参数
1 using System; 2 namespace Program 3 { 4 //提示用户输入用户名和密码,写一个方法来判断用户输入是否正确,返回给用户一个结果,并且 5 //还有单独返回给用户一个登录信息 6 //如果用户名错误,除了返回登录结果之外,还要返回一个“用户名错误” 7 //“密码错误” 8 class OutStudy 9 { 10 /// <summary> 11 /// 判断登录是否成功 12 /// </summary> 13 /// <param name="name">账号</param> 14 /// <param name="passport">密码</param> 15 /// <param name="msg">多余返回信息</param> 16 /// <returns>返回登录结果</returns> 17 public static bool IsLogin(string name,string passport,out string msg) 18 //返回登录名,返回密码,再多余返回个返回信息 19 { 20 21 if (name == "admin" && passport == "88888") 22 { 23 msg = "登录成功"; 24 return true; 25 } 26 else if (name == "admin") 27 { 28 msg = "密码错误"; 29 return false; 30 } 31 else if (passport == "88888") 32 { 33 msg = "用户名错误"; 34 return false; 35 } 36 else 37 { 38 msg = "未知错误"; 39 return false; 40 } 41 42 } 43 public static void Main() 44 { 45 Console.WriteLine("请输入用户名"); 46 string idname = Console.ReadLine(); 47 Console.WriteLine("请输入密码"); 48 string password = Console.ReadLine(); 49 string msg; 50 bool b=IsLogin(idname, password, out msg); 51 Console.WriteLine("登陆结果:{0}", b); 52 Console.WriteLine("登陆信息:{0}", msg); 53 Console.WriteLine(); 54 55 } 56 } 57 }

浙公网安备 33010602011771号