How to achieve method overloading in C#?
In C#, method overloading can be used to achieve multiple methods under the same method name with different parameter types or argument numbers. The steps to implement method overloading are as follows:
- Define multiple methods with the same method name, but with different parameter types or number of parameters.
- When calling a method, which overloaded method to call is determined by the type or number of parameters passed.
The following is an example of how to implement method overloading in code.
class OverloadExample
{
// 重载方法1:接受一个整数参数
public void MethodOverload(int num)
{
Console.WriteLine("整数参数:" + num);
}
// 重载方法2:接受一个字符串参数
public void MethodOverload(string str)
{
Console.WriteLine("字符串参数:" + str);
}
// 重载方法3:接受一个整数参数和一个字符串参数
public void MethodOverload(int num, string str)
{
Console.WriteLine("整数参数:" + num);
Console.WriteLine("字符串参数:" + str);
}
}
class Program
{
static void Main(string[] args)
{
OverloadExample example = new OverloadExample();
example.MethodOverload(10); // 调用重载方法1
example.MethodOverload("Hello"); // 调用重载方法2
example.MethodOverload(20, "World"); // 调用重载方法3
Console.ReadLine();
}
}
Output results:
整数参数:10
字符串参数:Hello
整数参数:20
字符串参数:World
By using method overloading, we can call the corresponding method based on different parameter types or quantities, improving the flexibility and readability of the code.