最近在编写代码时发现介绍C#参数默认值不能像PL/SQL那样直接设置default,网上也没有太多详细的资料,自己琢磨并试验后整理成果如下:

*
C#允许在函数声明部分定义默认值

*
参数默认值设定后,调用时可以不用填写有默认值的参数

*
参数传递顺序,顺序调用在前,指定参数调用在后

前期操作——在winform中添加一个button

 

1.默认参数设置

一般函数声明

public void FuncPara(string a,string b)

设置默认值

public void FuncPara(string a="specify by default a",string b= "specify by
default b")
public void FuncPara(string a="specify by default",string b= "specify by
default") { MessageBox.Show(a +"\n"+ b+"\n"); } private void
button1_Click(object sender, EventArgs e) { FuncPara(); }
此时调用函数将采用默认值

messagebox出来的是:

specify by default a

specify by default b

2.默认参数重写

2.1在方法体中重写
public void FuncPara(string a="specify by default",string b= "specify by
default") { b = "specify by function"; MessageBox.Show(a +"\n"+ b+"\n"); }
private void button1_Click(object sender, EventArgs e) { FuncPara(); }
此时调用函数a将采用默认值,b的值被重写了

messagebox出来的是:

specify by default a

specify by function

2.2在调用时重写
public void FuncPara(string a = "specify by default a", string b = "specify by
default b") { MessageBox.Show(a + "\n" + b + "\n"); } private void
button1_Click(object sender, EventArgs e) { FuncPara( b: "specify by call"); }
此时调用函数a将采用默认值,b的值在调用时被重写了

messagebox出来的是:

specify by default a

specify by call

3.参数传递时的顺序

原则先传顺序参数值,后传指定参数,没有指定参数的传值全部是按照顺序传递的

3.1顺序调用

这是最基本的参数调用方式,根据参数顺序传参,顺序参数在编写和调用时应当放在前面

编写函数首部时,有默认值参数一旦出现,后面的参数应当全部为有默认值的参数否则编译器会报错

正确写法
public void FuncPara(string c,string a="specify by default",string b= "specify
by default")
  调用时
FuncPara("c","a","b");
  依次向参数c,a,b传值

错误写法

public void FuncPara(string a="specify by default",string c,string b= "specify
by default")

3.2指定参数调用

你可以不按照顺序指定调用时的参数传值
public void FuncPara(string a="specify by default",string b= "specify by
default")
  只指定b,a采用默认值
FuncPara( b: "specify by call");
messagebox出来的是:

specify by default a

specify by call

 

  只重新指定参数a的值,b采用默认值
FuncPara( a: "specify by call");
messagebox出来的是:

specify by call

specify by default b

3.3混合调用
public void FuncPara(string d,string c,string a="specify by default",string b=
"specify by default") { b = "specify by function"; MessageBox.Show(a +"\n"+
b+"\n" + d + "\n" + c + "\n"); } private void button1_Click(object sender,
EventArgs e) { //调用时仅指定某一个参数的值其余采用默认值,可以混合顺序参数和指定参数传参 //顺序参数在前,指定参数通过在参数名后加冒号
FuncPara("this is para d","this is para c",b:"specify by call"); }
 

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:637538335
关注微信