方法
方法:就是将一堆代码进行重用的机制。
语法:public static 返回值类型 方法名 ([参数列表]){ 方法体; }
方法名:Pascal 每个单词的首字母都大写,其余字母小写。
参数列表:完成这个方法所必须要提供的条件。
返回值类型:如果不需要返回值,写void,如果需要写一个计算年龄的方法,那需要一个int类型的返回值类型。
return 在方法中的作用
1、在方法中返回要返回的值。
2、立即结束本次方法。
方法的调用语法:类名.方法名([参数]),Console.WriteLine
如果你写的方法跟Main()方法在同一个类中,调用方法时,类名是可以省略的。
示例:
using System; namespace 方法 { class Program { static void Main(string[] args) { //计算两个整数之间的最大值 int max= Program.GetMax(5,7); Console.WriteLine(max); Console.ReadKey(); } /// <summary> /// 计算两个整数之间的最大值并且将最大值返回 /// </summary> /// <param name="n1">第一个整数</param> /// <param name="n2">第二个整数</param> /// <returns>将最大值返回</returns> public static int GetMax(int n1,int n2) { //三元表达式:如果n1大于n2,则n1就是整个三元表达式的值,否则就是n2. return n1 > n2 ? n1 : n2; } } }
传参:
我们在Main函数中,调用Test函数,我们管Main称为调用者,管Test函数称为被调用者。
如果被调用者想要得到调用者的值:
1、传递参数
using System; namespace 方法 { class Program { static void Main(string[] args) { int a = 3; Test(a);//调用Test方法 Console.WriteLine(a); Console.ReadKey(); } //这是一个无返回值类型的Test方法,而Main方法调用Test方法时又需要一个参数, //我们需要把Main方法的参数传给Test,这就是传参的过程。 public static void Test(int a) //int a 作为参数传给了Test函数 { a = a + 5; } } }
2、使用静态字段类模拟全局变量。
using System; namespace 方法 { class Program { public static int _number = 10;//全局变量字段 static void Main(string[] args) { TestTwo(); } public static void TestTwo() { Console.WriteLine(_number); } } }
如果调用者想要得到被调用者的值:
1)return回去
using System; namespace 方法 { class Program { static void Main(string[] args) { int a = 3; int res = Test(a); Console.WriteLine(res); Console.ReadKey(); } public static int Test(int a) { a = a + 5; return a;//把a的值返回,让Main方法调用使用 } } }
判断是否是闰年的练习:
using System; namespace 判断闰年的练习 { class Program { static void Main(string[] args) { bool b= IsRun(2000);//输入实参 Console.WriteLine(b); Console.ReadKey(); } public static bool IsRun(int year)//把Main的实参传进来 { bool b = (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0); return b; } } }

浙公网安备 33010602011771号