using System; namespace Lesson7_函数 { class Program { #region 知识点一 基本概念 //函数(方法) //本质是一块具有名称的代码块 //可以使用函数(方法)的名称来调用它 //函数(方法)是封装代码进行重复使用的手段 //函数(方法)的主要作用 //1.封装代码 //2.提高代码的复用性 //3.抽象行为 #endregion #region 知识点二 函数写在哪里 //1.class类里面 //2.struct结构体里面 #endregion #region 知识点三 基本语法 //4个部分 // 1 2 3 4 // static 返回类型 函数名(参数类型 参数名1,参数类型 参数名2.......) // { // 函数体(代码) // 5(可选,根据返回类型) // return 返回值; // } //1 static //不是必须的 在没有学习类和结构体之前 先统一写上 //2.1 返回类型 //void 表示没有返回值 //返回类型可以是任何数据类型 14种变量类型+复杂数据类型(数组、枚举、结构体) //3 函数名 //使用帕斯卡命名法(PascalCase) 每个单词首字母大写 //4.1 参数列表 //不是必须的,可以没有参数 多个参数时,使用逗号间隔 参数类型也可以是任何数据类型 //4.2 参数的命名 //使用驼峰命名法(camelCase) 第一个单词首字 //5 return //当返回类型不是void时 必须使用return语句 来返回一个与返回类型匹配的值 //void也可以使用return 但不能返回任何值 只能单独使用return来结束函数 #endregion #region 知识点四 实际运用 //1.无参无返回值 static void SayHello() { Console.WriteLine("Hello World"); //return; //可选 } //2.有参无返回值 static void SayYourName(string name) { Console.WriteLine("Hello " + name); } //3.无参有返回值 static string WhatsYourName() { return "王五"; } //4.有参有返回值 static int Sum(int a,int b) { return a + b;//return后面可以是一个表达式 } //5.有参有返回值(多个参数) //函数的返回值只能有一个,多个返回值时,可以使用数组、结构体、类等复杂数据类型来实现 static float[] AverageAndSum(int a, int b) { int sum = a + b; float avg = (a + b) / 2.0f; return new float[] { sum, avg}; } #endregion #region 知识点五 关于return //即使函数没有返回值,也可以使用return //return可以直接不执行return后的代码,直接结束函数 static void Speek(string str) { if (str == "脏话") { return; } else { Console.WriteLine(str); } } #endregion static void Main(string[] args) { //调用函数 //函数名(参数); SayHello(); Console.WriteLine(); //传入一个string类型的参数 string str = "张三"; SayYourName(str); //直接传入一个string类型的值 SayYourName("李四"); Console.WriteLine(); //接收WhatsYourName的返回值并传入SayYourName SayYourName(WhatsYourName()); Console.WriteLine(); //一般来说 //有返回值的函数 直接拿返回值使用 或 拿变量接收返回值 string str2 = WhatsYourName(); //也可以直接调用,但没有任何意义 WhatsYourName(); //传入两个int类型的参数 让Sum函数运算 并接打印返回值 Console.WriteLine(Sum(10, 20)); Console.WriteLine(); float[] arr = AverageAndSum(5, 7); Console.WriteLine("sum" + arr[0] + "\t" + "avg" + arr[1]); Console.WriteLine(); Console.WriteLine("return:"); Speek("脏话");//不会返回脏话 Console.WriteLine("不return"); Speek("好话"); } } }