Unity 3D游戏开发 - C#语法基础 | 函数之函数重载
其他
2018-08-28 22:51:13
阅读次数: 0
函数练习
- 封装 int 类型一维数组相关操作函数
- 无参数无返回值。定义一个ShowTitle()函数,输出显示本次演示的题目。
static void Main(string[] args)
{
int[] intA = new int[] { 12, 34, 56, 78 };
ShowTitle();
Console.ReadKey();
}
static void ShowTitle()
{
Console.WriteLine("封装 int 类型一维数组相关操作函数");
}
- 有参数无返回值。声明一个ForArray()函数,遍历输出某个数组的元素。
static void Main(string[] args)
{
int[] intA = new int[] { 12, 34, 56, 78 };
ForArray(intA);
Console.ReadKey();
}
static void ForArray(int[] intArray)
{
for(int i = 0; i < intArray.Length; i++)
{
Console.WriteLine(intArray[i]);
}
}
- 有参数有返回值。声明一个GetArrayLength()函数,用于获取某个数组的元素个数。
static void Main(string[] args)
{
int[] intA = new int[] { 12, 34, 56, 78 };
int length = GetArrayLength(intA);
Console.WriteLine("当前数组元素个数为:" + length);
Console.ReadKey();
}
static int GetArrayLength(int[] intArray)
{
return intArray.Length;
}
函数重载
- 定义
- 函数名称相同,但参数列表不同。
- 调用该函数时,会根据不同的参数,自动选择合适的函数重载形式。
- 练习:定义一个Add方法,实现整数,小数相加操作。
- 未使用函数重载时(过程繁琐)
static void Main(string[] args)
{
int a = Add1(5, 10);
Console.WriteLine(a);
Console.WriteLine(Add2(1.111, 2.222));
Console.WriteLine(Add3(3.1415926, 10));
Console.ReadKey();
}
static int Add1(int a, int b)
{
return a + b;
}
static double Add2(double a, double b)
{
return a + b;
}
static double Add3(double a, int b)
{
return a + b;
}
- 使用函数重载(调用简单些)
static void Main(string[] args)
{
Console.WriteLine(Add(1.3333, 2.2222));
Console.WriteLine(Add(2, 8));
Console.WriteLine(Add(1.111, 10));
Console.ReadKey();
}
static int Add(int a, int b)
{
return a + b;
}
static double Add(double a, double b)
{
return a + b;
}
static double Add(double a, int b)
{
return a + b;
}
- 参数不同的情况
- 参数个数相同,则参数类型不能相同。
- 参数类型相同,则参数个数不能相同。
- 函数的返回值和重载无关。
转载自blog.csdn.net/weixin_41232641/article/details/81983542