命名参数(C#)

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

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

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


看下面一个例子:

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值