什么是C#中的方法重载?
具有相同名称但参数不同的两个或两个以上方法在C#中称为方法重载。
可以通过更改参数的数量和参数的数据类型来执行C#中的方法重载。
假设您有一个输出数字乘法的函数,那么我们的重载方法将具有相同的名称,但参数数量不同-
public static int mulDisplay(int one, int two) { } public static int mulDisplay(int one, int two, int three) { } public static int mulDisplay(int one, int two, int three, int four) { }
以下是显示如何实现方法重载的示例-
示例
using System; public class Demo { public static int mulDisplay(int one, int two) { return one * two; } public static int mulDisplay(int one, int two, int three) { return one * two * three; } public static int mulDisplay(int one, int two, int three, int four) { return one * two * three * four; } } public class Program { public static void Main() { Console.WriteLine("Multiplication of two numbers: "+Demo.mulDisplay(10, 15)); Console.WriteLine("Multiplication of three numbers: "+Demo.mulDisplay(8, 13, 20)); Console.WriteLine("Multiplication of four numbers: "+Demo.mulDisplay(3, 7, 10, 7)); } }
输出结果
Multiplication of two numbers: 150 Multiplication of three numbers: 2080 Multiplication of four numbers: 1470