命名参数(C#)

来源:互联网 发布:小米2s3g网络设置 编辑:程序博客网 时间:2024/05/15 23:46

命名参数,调用者可以显式为一个参数赋值。

命名参数打破了只能依据参数顺序决定哪个值赋给哪个参数的限制。利用命名参数,再结合可选参数,参数的个数和

顺序都可以随意根据实际要求进行控制。


看下面一个例子:

public NamedParaExample(){    this.InitializeComponent();    //看作是可选参数    txtblk1.Text = DisplayPhoneInfo("微软");    //看作是命名参数    txtblk2.Text = DisplayPhoneInfo(brand: "微软");    //看作是可选参数    txtblk3.Text = DisplayPhoneInfo("小米", 699);    //看作是命名参数    //txtblk4.Text = DisplayPhoneInfo(brand: "小米", 699);此种写法错误。看作命名参数,那么所有参数的格式都要是命名参数的调用格式    txtblk4.Text = DisplayPhoneInfo(brand: "小米", price: 699);    //看作是可选参数(本意是想让价格保持默认值,只指定品牌和系统)    //不过明显是不对的,限制在于只能依照参数顺序决定参数赋值    //txtblk5.Text = DisplayPhoneInfo("魅族", "Flyme OS");    txtblk5.Text = DisplayPhoneInfo(brand: "魅族", operationSystem: "Flyme OS");//命名参数完全打破需要依照参数顺序来决定赋值的弊端    //命名参数的顺序可以无关,只要指定参数名即可    txtblk6.Text = DisplayPhoneInfo(price: 1099, brand: "乐视", operationSystem: "eUI");    txtblk7.Text = DisplayPhoneInfo("华为", 5);    txtblk8.Text = DisplayPhoneInfo(screenSize: 6, producer: "中兴");}string DisplayPhoneInfo(string brand,int price = default(int),string operationSystem = default(string)){    string result = "手机信息";    result = string.Format("手机品牌:{0},手机价格:{1},手机系统:{2}",brand,price,operationSystem);    return result;}//下面的方法定义是错的,可选参数的差异不构成重载//string DisplayPhoneInfo(string brand, int price, string operationSystem) { }string DisplayPhoneInfo(string producer,int screenSize){    string result = "手机信息";    result = string.Format("手机厂商:{0},手机屏幕:{1}寸",producer,screenSize);    return result;}

结果截图:

1 0