5、通过重载方法定义交换两个实数类型变量值的函数和交换两个字符串类型变量值的函数,并
创建应用程序调用。
重载(Overload)是指在一个类中可以定义多个同名但参数类型、个数或顺序不同的方法。重载方法可以在不同的情况下使用不同的参数列表来执行相同的操作。重载方法可以提高代码的复用性和灵活性,使得程序更加简洁、高效。
比如如下示例代码:
using System;
public class Calculator {
public int Add(int a, int b) { // 定义两个整数相加的方法
return a + b;
}
public double Add(double a, double b) { // 定义两个实数相加的方法
return a + b;
}
public int Add(int a, int b, int c) { // 定义三个整数相加的方法
return a + b + c;
}
public static void Main(string[] args) {
Calculator calculator = new Calculator();
Console.WriteLine("1 + 2 = " + calculator.Add(1, 2)); // 调用两个整数相加的方法
Console.WriteLine("1.5 + 2.5 = " + calculator.Add(1.5, 2.5)); // 调用两个实数相加的方法
Console.WriteLine("1 + 2 + 3 = " + calculator.Add(1, 2, 3)); // 调用三个整数相加的方法
}
}
using System;
class Program {
static void Swap(ref float a, ref float b) {
float temp = a;
a = b;
b = temp;
}
static void Swap(ref string a, ref string b) {
string temp = a;
a = b;
b = temp;
}
static void Main(string[] args) {
float x = 3.14f;
float y = 2.71f;
Console.WriteLine("Before swap: x = {0}, y = {1}", x, y);
Swap(ref x, ref y);
Console.WriteLine("After swap: x = {0}, y = {1}", x, y);
string s1 = "hello";
string s2 = "world";
Console.WriteLine("Before swap: s1 = {0}, s2 = {1}", s1, s2);
Swap(ref s1, ref s2);
Console.WriteLine("After swap: s1 = {0}, s2 = {1}", s1, s2);
}
}
Swap 方法分别定义了两个参数为 float 类型和两个参数为 string 类型的版本,用于交换实数类型变量和字符串类型变量的值。在 Main 方法中,分别调用了这两个方法,并打印输出了交换前后变量的值,以验证函数的正确性。