函數的重載,及同一個類中方法名相同,參數列表不同,參數列表不同包括方法中的參數個數不同或參數的數據類型不同
首先說一種常見的重載,修改參數的個數和數據類型
[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);
}
}
}