C# 6.0 (C# vNext) 新功能之:Declaration Expressions

Declaration Expressions 应该是叫宣告表达式。
直接看代码。
原先我们常写如下的式子:
long id;
if (!long.TryParse(Request.QureyString["Id"], out id))
{ }

先在外面宣告一个 long 型态的变量 id,再在 long.TryParse 裹使用他

现在可以直接写成:
if (!long.TryParse(Request.QureyString["Id"], out long id))
{ }

这是另一个例子,直接在方法裹宣告变数类型 result
return int.TryParse(input, out var result) ? result : 0;

另外一个例子,先将 user.HomeAddress 指定给 address,接著再判断 address 是否为 null
if ((var address = user.HomeAddress) != null)
{
    // work with address ... 
    return address.City;
}

又是另外一个例子,在 foreach 裹宣告 var odd
int result = 0;
foreach (var n in var odd = numbers.Where(n => n % 2 == 1).ToList())
{ 
    result += n + odd.Count();
}
return result;

另外一个例子:
public string FormatMessage(string attributeName)
{
  string result;
  if(!Enum.TryParse<FileAttributes>(attributeName, out var attributeValue) )
  {
    result = string.Format(
      "'{0}' is not one of the possible {2} option combinations ({1})",
      attributeName, string.Join(",", string[] fileAtrributeNames =
      Enum.GetNames(typeof (FileAttributes))),
      fileAtrributeNames.Length);
  }
  else
  {
    result = string.Format("'{0}' has a corresponding value of {1}",
    attributeName, attributeValue);
  }
  return result;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值