C#学习4
函数的重载,及同一个类中方法名相同,参数列表不同,参数列表不同包括方法中的参数个数不同或参数的数据类型不同
首先说一种常见的重载,修改参数的个数和数据类型
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace chongzai
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.run();
}
void run()
{
int arg1 = 10;
float arg2 = 12.5f;
int arg3 = 30;
dowork(arg1, arg2);
dowork(arg1, arg2, arg3);
dowork(arg2, arg3);
}
void dowork(int intdata, float floatdata, int moreintdata)
{
Console.WriteLine("intdata:{0},floatdata:{1},moredata:{2}", intdata, floatdata, moreintdata);
}
void dowork(int intdata, float floatdata)
{
Console.WriteLine("intdata:{0},floatdata:{1}", intdata, floatdata);
}
void dowork(float floatdata, int moreintdata)
{
Console.WriteLine("floatdata:{0},moreintdata:{1}", floatdata, moreintdata);
}
}
}
也可以通过给参数赋上默认值来进行重载,注意没有默认值的参数写在前面,有默认值的参数写在后面
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace chongzai
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.run();
}
void run()
{
int arg1 = 10;
float arg2 = 12.5f;
int arg3 = 30;
dowork(arg1);
dowork(arg1, arg2);
dowork(arg1, arg2, arg3);
dowork();
}
void dowork(int intdata=0, float floatdata=0.0f, int moreintdata=0)
{
Console.WriteLine("intdata:{0},floatdata:{1},moredata:{2}", intdata, floatdata, moreintdata);
}
}
}
还也通过指定参数的传值来重载
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace chongzai
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.run();
}
void run()
{
int arg1 = 10;
float arg2 = 12.5f;
int arg3 = 30;
dowork(arg1);
dowork(moreintdata:arg3);
dowork(arg1, arg2);
dowork(floatdata:arg2,moreintdata:arg3);
dowork(arg1, arg2, arg3);
dowork();
}
void dowork(int intdata=0, float floatdata=0.0f, int moreintdata=0)
{
Console.WriteLine("intdata:{0},floatdata:{1},moredata:{2}", intdata, floatdata, moreintdata);
}
}
}
补充:软件开发 , C# ,