方法(函数)
一 概念
什么是方法(函数)?
可以把方法 理解为一个代码块。
可以解决问题的,独立执行的代码块
方法:可以封装具体实现,让程序员不用关心具体实现。
方法的存在,便于模块化编程。
二 方法的分类
-
没有参数的方法
public static void Add() { int a = 1; int b = 2; int result = a + b; Console.WriteLine(result); }
-
有参数的方法
public static void Add2(int num1, int num2) { int c = num1 + num2; Console.WriteLine("c 的值是 "+c); }
-
没有返回值的方法
public static void Add2(int a, int b) { int c = a + b; Console.WriteLine("c 的值是 "+c); } //计算两个数字的和 //无参方法 没有参数 public static void Add() { int a = 1; int b = 2; int result = a + b; Console.WriteLine(result); }
-
有返回值的方法
public static int Add2(int a, int b) { int c = a + b; return c; } int a = 10; int b =11; int c = 12; int temp = Add2(a,b); int result = Add2(c, temp); Console.WriteLine(result); public static int Add2(int a, int b) { int c = a + b; return c; } public static double Add3(double a, double b) { double c = a + b; return c; } public static string Add4(string a, string b) { string c = a + b; return c; }
三 基本语法
public static void Add() { } Add: 是方法的名字 定义方法的时候,必须带 ()
using day02; internal class Program { private static void Main(string[] args) { // 排序 从小到大进行排序 // int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int[] nums = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; //方法的调用 // Sort(nums); //方法的调用 // Add(); int a = 10; int b =11; int c = 12; int temp = Add2(a,b); int result = Add2(c, temp); Console.WriteLine(result); } public static int Add2(int a, int b) { int c = a + b; return c; } public static double Add3(double a, double b) { double c = a + b; return c; } public static string Add4(string a, string b) { string c = a + b; return c; } //计算两个数字的和 //无参方法 没有参数 public static void Add() { int a = 1; int b = 2; int result = a + b; Console.WriteLine(result); } //排序方法 public static void Sort(int[] nums) { Console.WriteLine("=============================="); for (int j = 0; j < nums.Length - 1; j++) { //每次出来一个最大值 for (int i = 0; i < nums.Length - 1; i++) { if (nums[i] > nums[i + 1]) { //交换位置 int temp = nums[i]; nums[i] = nums[i + 1]; nums[i + 1] = temp; } } } for (int i = 0; i < nums.Length; i++) { Console.Write(nums[i] + " "); } Console.WriteLine(); } }