param的用法!以及操作符的重载(C#)

来源:百度知道 编辑:UC知道 时间:2024/05/02 20:33:00
以及操作符如何被调用

param
e.g.
如果你想要两个数相加的函数。
int Add(int a,int b){return a+b;}
如果你想做三个数相加的函数。
int Add(int a,int b,int c){return a+b+c;}
如果……四个……五个…………
然后你疯了。

你会发现把参数改成数组比较好。
int Add(int[] args)
{
int sum=0;
foreach(int number in args)
{
sum+=number;

return sum;
}
但是使用就不方便了,如果你想要用Add(1,2),非要把1,2放到数组里。
这时可以把上面那个方法加上params.
即 int Add(params int[] args){......}
之后在使用的时候只需 Add(1,2), Add(7,8,9,10,12) ……

操作符重载:
如果你想 知道1+1等于多少,
那么 int a=1+1;
但如果你想 知道男人+女人等于多少……
C#不知道等于孩子,但是你知道。
所以你必须亲自等义这个 “+” 是什么意思。
e.g.
class Man
{
public string Name;
//运算符重载 +
public static Child operator+(Man father,Woman mother)
{
Child baby=new Child();
baby.Father=father.Name;
baby.Mother=mother.Name;
return baby;
}

}
class Woman