1、方法 重载
使用方法重载时,多个方法可以使用不同的参数使用相同的名称:
例如:
int MyMethod(int x)
float MyMethod(float x)
double MyMethod(double x, double y)
下面的示例是两个两种不同类型数字的方法:
例如:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication { class Program { static int PlusMethodInt(int x, int y) { return x + y; } static double PlusMethodDouble(double x, double y) { return x + y; } static void Main(string[] args) { int myNum1 = PlusMethodInt(8, 5); double myNum2 = PlusMethodDouble(4.3, 6.26); Console.WriteLine("int: " + myNum1); Console.WriteLine("double: " + myNum2); } } }
与其定义应该执行相同操作的两个方法,不如重载一个方法。
在下面的示例中,我们重载了PlusMethod
方法,使其同时适用于int
和double
:
例如:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication { class Program { static int PlusMethod(int x, int y) { return x + y; } static double PlusMethod(double x, double y) { return x + y; } static void Main(string[] args) { int myNum1 = PlusMethod(8, 5); double myNum2 = PlusMethod(4.3, 6.26); Console.WriteLine("int: " + myNum1); Console.WriteLine("double: " + myNum2); } } }
注意:只要参数的数量或类型不同,多个方法就可以具有相同的名称。
2、通过参数个数不同
C# 方法重载时区分方法签名(Method Signature),而方法签名包含方法名称和参数列表。当参数个数不同时,方法签名不同,因此可以成功重载。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication { class Program { // 只有一个参数 public void Print(int a) { Console.WriteLine("整数: " + a); } // 两个参数 public void Print(int a, int b) { Console.WriteLine("两个整数: " + a + " 和 " + b); } static void Main() { Program obj = new Program(); obj.Print(5); // 调用 Print(int a) obj.Print(10, 20); // 调用 Print(int a, int b) } } }
3、通过参数类型不同
方法重载(Method Overloading)可以通过参数类型不同来实现,即方法的名称相同,但参数的类型不同,从而让编译器在调用时能够区分不同的方法。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication { class Program { public void Display(int a) { Console.WriteLine("整数: " + a); } public void Display(double b) { Console.WriteLine("浮点数: " + b); } static void Main() { Program obj = new Program(); obj.Display(5); // 调用 Display(int a) obj.Display(3.14); // 调用 Display(double b) } } }
4、通过参数顺序不同
C# 方法重载(Method Overloading)中,可以通过参数顺序不同来实现多个方法的重载。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication { class Program { public void Show(int a, string b) { Console.WriteLine("整型: " + a + ", 字符串: " + b); } public void Show(string b, int a) { Console.WriteLine("字符串: " + b + ", 整型: " + a); } static void Main() { Program obj = new Program(); obj.Show(10, "Hello"); // 调用 Show(int, string) obj.Show("World", 20); // 调用 Show(string, int) } } }