C#_基础_方法以及方法重载(十)

方法:就是将一段代码放在一起,进行重复调用的机制。

语法:

             * [private] static 返回值类型 函数名 (参数列表)
             * {
             *      函数代码;
             *      
             * return  返回值;
             * }
             *
             *      public :是访问修饰符,公共的在那都可以访问
             *      static: 静态的
             *      返回值类型:如果没有返回值就void
             *      方法名: 首字母大写,其余小写
             *      参数列表:完成这个方法所必须要提供这个方法的条件
             *      return作用 :1.结束方法; 2.在方法中返回要返回的值

 1 练习1: 计算两个整数之间的最大值
 2         /// <summary>
 3         /// 比较两个整数的大小,并且返回最大值
 4         /// </summary>
 5         /// <param name="num1">整数</param>
 6         /// <param name="num2">整数</param>
 7         /// <returns></returns>
 8         public static int GetMax(int num1, int num2)
 9         {
10             return num1 > num2 ? num1 : num2;
11         }
12 
13 练习题2:读取输入的整数,如果用户输入的是数字则返回,否则提示用户重新输入
14         public static void GetInt()
15         {
16             while (true)
17             {
18                string s = Console.ReadLine();
19                 try
20                 {
21                     int num = Convert.ToInt32(s);
22                     Console.WriteLine(num);
23                     break;
24                 }
25                 catch 
26                 {
27                     Console.WriteLine("输入错误,重新输入");
28                    
29                 }
30             }
31 练习题3:判断是否是闰年
32     public static bool  IsRun( int year)
33         {
34             bool b = (year / 400 == 0) || (year / 4 == 0 && year % 100 == 0);
35             return b;
36         }
练习题

方法重载:

  概念:方法名相同,参数列表不同(参数类型,参数个数)

 1         ///比较两个数最大值
 2         public static int GetMax(int num1, int num2)
 3         {
 4             return num1 > num2 ? num1 : num2;
 5         }
 6         //三个数最大值
 7         public int GetMax(int num1, int num2,int num3)
 8         {
 9             int temp = num1 > num2 ? num1 : num2;
10             return temp > num3 ? temp : num3;
11         }
原文地址:https://www.cnblogs.com/CeasarH/p/9164088.html