在具有相同名称但具有不同参数列表的类中定义多个方法时。此方法参数在参数的数量、类型和顺序上必须不同。这称为方法重载。方法重载是多态性的一种形式。
C#中的方法重载
以下是在 C# 中使用方法重载的语法:
public class FruitUtility
{
// Method with no parameters
public int AddFruitPrice()
{
return 0;
}
// Method with two integer parameters
public int AddFruitPrice(int price1, int price2)
{
return price1 + price2;
}
// Method with three double parameters
public double AddFruitPrice(double price1, double price2, double price3)
{
return price1 + price2 + price3;
}
// Method with a different parameter type
public string AddFruitPrice(string a, string b)
{
return a +" "\+ b;
}
}
在此示例中,我们有一个 FruitUtility 类,其中包含多个 AddFruitPrice 方法,每个方法都有不同的参数列表。以下是有关方法重载的一些要点:
方法签名由方法名称和参数列表(包括参数名称及其数据类型)组成。方法重载的方法签名必须不同。
方法重载可以具有相同或不同的返回类型。返回类型本身并不能确定方法是否重载。
在方法重载中,参数的数量、类型和顺序可以不同。在上面的示例中,我们有具有不同参数编号和不同数据类型的重载。
当编译器根据方法的数量、类型和顺序确定首先调用哪个方法以及以哪个顺序调用时,称为编译时或静态方法的重载方法。
下面介绍如何使用重载方法:
FruitUtility fruit = new FruitUtility();
int result1 = fruit.AddFruitPrice(); // Calls the parameterless Add method
int result2 = fruit.AddFruitPrice(5, 3); // Calls the Add method with two integers
double result3 = fruit.AddFruitPrice(1.1, 2.2, 3.3); // Calls the Add method with three doubles
string result4 = fruit.AddFruitPrice("Apple", "Mango"); // Calls the Add method with two string
using System;
public class Program
{
public static void Main(string[] args)
{
FruitUtility fruit = new FruitUtility();
int result1 = fruit.AddFruitPrice(); // Calls the parameterless Add method
int result2 = fruit.AddFruitPrice(5, 3); // Calls the Add method with two integers
double result3 = fruit.AddFruitPrice(1.1, 2.2, 3.3); // Calls the Add method with three doubles
string result4 = fruit.AddFruitPrice("Apple", "Mango"); // Calls the Add method with two string
Console.WriteLine("Result One is = {0}", result1);
Console.WriteLine("Result Two is = {0}", result2);
Console.WriteLine("Result Three is = {0}", result3);
Console.WriteLine("Result Four is = {0}", result4);
}
}
public class FruitUtility
{
// Method with no parameters
public int AddFruitPrice()
{
return 0;
}
// Method with two integer parameters
public int AddFruitPrice(int price1, int price2)
{
return price1 + price2;
}
// Method with three double parameters
public double AddFruitPrice(double price1, double price2, double price3)
{
return price1 + price2 + price3;
}
// Method with a different parameter type
public string AddFruitPrice(string a, string b)
{
return a +" "+ b;
}
}
Result One is = 0
Result Two is = 8
Result Three is = 6.6
Result Four is = Apple Mango
通过在类中使用方法重载,可以提高代码的可用性。方法重载提供了使用结构,您可以使用该结构创建具有相同名称的方法,这些方法执行逻辑相关的操作,但接受不同的输入或根据提供的参数生成不同的结果。