在具有相同名称但具有不同参数列表的类中定义多个方法时。此方法参数在参数的数量、类型和顺序上必须不同。这称为方法重载。方法重载是多态性的一种形式。
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;
}
}
在此示例中方法重载,我们有一个 类,其中包含多个 方法,每个方法都有不同的参数列表。以下是有关方法重载的一些要点:
1. 方法签名:
方法签名由方法名称和参数列表(包括参数名称及其数据类型)组成。方法重载的方法签名必须不同。
2.返回类型:
方法重载可以具有相同或不同的返回类型。返回类型本身并不能确定方法是否重载。
3. 参数列表:
在方法重载中,参数的数量、类型和顺序可以不同。在上面的示例中,我们有具有不同参数编号和不同数据类型的重载。
4. 编译时分辨率:
当编译器根据方法的数量、类型和顺序确定首先调用哪个方法以及以哪个顺序调用时,称为编译时或静态方法的重载方法。
下面介绍如何使用重载方法:
例
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
C# 中的方法重载(示例)
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
通过在类中使用方法重载,可以提高代码的可用性。方法重载提供了使用结构,您可以使用该结构创建具有相同名称的方法方法重载,这些方法执行逻辑相关的操作,但接受不同的输入或根据提供的参数生成不同的结果。
限时特惠:本站持续每日更新海量各大内部创业课程,一年会员仅需要98元,全站资源免费下载
点击查看详情
站长微信:Jiucxh
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。