VS2015预览版中的C#6.0 新功能(二)

VS2015预览版中的C#6.0 新功能(三)

VS2015的预览版在11月12日发布了,下面让我们来看看C#都提供了哪些新的功能。

字符串添写(String interpolation)
      在格式化字符串时,string.Format是经常被用到的,它确实很方便使用,但是这种使用占位符,然后通过参数替换的方式还不够方便, 在C#6.0里,String interpolation语法的引入提供了另一种格式化字符串的方式。请看下面的例子:
假设我们现在有个如下所示的Book类,现在需要格式化它的字段以输出关于该book的描述。

public class Book
{
public int Number { get; set; } public string Name { get; set; } public string Abstract { get; set; } public float Price { get; set; } public List<Author> Authors { get; set; }
}

使用string.Format的代码如下:

var introUsingStringFormat = string.Format("[{0}]' price is {1:F3}, its description is {2}.", book.Name, book.Price, book.Abstract);

使用string interpolation的代码如下:

var introUsingStrInterPolation = "[\{book.Name}]' price is \{book.Price : F3}, its description is \{book.Abstract}.";

完整的程序如下:

public void Show()
{
//interpolate string
var book = new Book
{
Abstract = "Book about C#6.0",
Name = "C#6.0 new feature",
Price = 10.8709f,
}; var introUsingStrInterPolation = "[\{book.Name}]' price is \{book.Price : F3}, its description is \{book.Abstract}.";
var introUsingStringFormat = string.Format("[{0}]' price is {1:F3}, its description is {2}.", book.Name, book.Price, book.Abstract);
Console.WriteLine("format string using string interpolation:");
Console.WriteLine(introUsingStrInterPolation);
Console.WriteLine("===============================================================================");
Console.WriteLine("format string using string.Format method:");
Console.WriteLine(introUsingStringFormat);
Console.Read();
}

如下图,两种方式的输出是一样的:

总结:

String Interpolation语法允许你在字符串里直接插入代码并可以像string.Format 那样指定format Specifier和对齐,如上面的例子\{book.Price : F3}指定price的精度为3。这个语法在之后版本中会变得更加简洁,可能会采用如下的格式:

var introUsingStrInterPolation = $"[{book.Name}]' price is {book.Price : F3}, its description is {book.Abstract}.";

空条件运算符?

如下面例子所示, 在程序中经常会出现对表达式中对象是否为空的连续检测。

 if (book != null && book.Authors != null)
{
var countOfAuthers = book.Authors.Count;
}

空条件运算符?使得这种检测更加方便,表达更加简洁,其使用方法如下:

var countOfAuthersUsingNullConditional = book?.Authors?.Count;

空条件运算符?用在成员运算符.和索引前面,会执行下面的操作:
 如果其前面的对象为空,那么直接返回null,否则允许访问前面对象的成员或者元素以继续后面运算,所以上面的表达式和下面的代码段是等价的

 if (book == null)
{
countOfAuthorsUsingNullConditional = null;
}
else if (book.Authors == null)
{
countOfAuthorsUsingNullConditional = null;
}
else
{
countOfAuthorsUsingNullConditional = book.Authors.Count;
}

上面的code展示了其执行的逻辑顺序,达到相同结果的简洁写法如下:

if(book == null || book.Authors == null)
{
countOfAuthorsUsingNullConditional = null;
}
else
{
countOfAuthorsUsingNullConditional = book.Authors.Count;
}

从上可以看出其具有如下特性:

  1. 包含?的表达式返回的是引用类型
  2. ?具有类似逻辑运算符||和&&的短路逻辑
  3. ?自己可以组成链,正如上面例子所示的,在同一表达式中连续使用?

此外,空条件运算符还具有如下特点:

  1. 对其前面的对象是否为空只进行一次计算
  2. 可以与合并运算符??一起使用更加方便
  3. ?后面不能直接跟随使用()的方法调用,对于event或者delegate可以使用?.Invoke的方式来使用,由于?只计算其右边部分一次并把其保存到临时变量中,所以它是线程安全的

下面来看一些针对2和3的例子:

//using with coalescing operator ??
int numberOfAuthors = book?.Authors?.Count ?? ; //using with delegate.
action?.Invoke();

完整的程序如下:

public void Show()
{
//traditional way
if (book != null && book.Authors != null)
{
var countOfAuthors = book.Authors.Count;
Console.WriteLine("===================using tranditional way==============");
Console.WriteLine(countOfAuthors);
} //the way of using null-conditional operator.
var countOfAuthorsUsingNullConditional = book?.Authors?.Count;
Console.WriteLine("===================null-conditional operator==============");
Console.WriteLine(countOfAuthorsUsingNullConditional);
Console.Read(); //the logic of the expression.
if (book == null)
{
countOfAuthorsUsingNullConditional = null;
}
else if (book.Authors == null)
{
countOfAuthorsUsingNullConditional = null;
}
else
{
countOfAuthorsUsingNullConditional = book.Authors.Count;
}
//the concise edition using tranditional way.
if (book == null || book.Authors == null)
{
countOfAuthorsUsingNullConditional = null;
}
else
{
countOfAuthorsUsingNullConditional = book.Authors.Count;
}
//using with coalescing operator ??
int numberOfAuthors = book?.Authors?.Count ?? ; //using with delegate.
action?.Invoke();
}

nameof表达式

有时候我们需要获得代码中某些symbol的名字,例如在throw ArgumentNullException时,需要获得为null参数的名字(字符串形式),在调用PropertyChanged时,我们也需要获得属性的名字,直接使用字符串具有如下的缺点:

  1. 容易拼写错误
  2. 无法重构
  3. 没有语法检查

nameof表达式能够以字符串的形式返回参数对象或者类成员的名字,下面是一些例子

 var nameOfClassPropertyObject = nameof(book);
var nameOfArgument = nameof(author);
var classMethodMember = nameof(Book.Equals);
var classPropertyMember = nameof(Book.Number);
var @class =  nameof(Book);

从上面的例子中可以看出nameof运算符可以用于类(包括attribute类),类的成员,对象上,另外需要注意的是它只会输出最终元素的名字不会包含其前缀,例如nameof(Book.Equals)的输出是Equals。

VS2015预览版中的C#6.0 新功能(一)的更多相关文章

  1. VS2015预览版中的C#6.0 新功能(二)

    VS2015预览版中的C#6.0 新功能(一) VS2015预览版中的C#6.0 新功能(三) 自动属性的增强 只读自动属性 以前自动属性必须同时提供setter和getter方法,因而只读属性只能通 ...

  2. VS2015预览版中的C#6.0 新功能(三)

    VS2015预览版中的C#6.0 新功能(一) VS2015预览版中的C#6.0 新功能(二) Using static 使用using StaticClass,你可以访问StaticClass类里的 ...

  3. VS2015预览版体验

    .NET开源了,JAVA颤抖吧... 据说VS2015可以开发android,ios,wp应用程序了,还可以开发能运行在mac,linux上的ASP.NET网站,如果真是这样就太爽啦,上微软官网下载了 ...

  4. Windows 10 开发人员预览版中的新增功能(转自 IT之家)

    Windows 10 开发人员预览版中的新增功能 在Win10预览版中安装工具与SDK后,即可着手创建Windows通用应用或先浏览目前的环境与此前相比都发生了什么变化. 应用建模 文件资源管理器: ...

  5. 关于在Visual Studio 2019预览版中的用户体验和界面的变化

    原文地址:https://blogs.msdn.microsoft.com/visualstudio/2018/11/12/a-preview-of-ux-and-ui-changes-in-visu ...

  6. 根据 Power BI Desktop(预览版)中的报表页创建工具提示

    根据 Power BI Desktop 中创建的报表页,可创建直观丰富的报表工具提示,这些提示在你将鼠标悬停在视觉对象上时显示. 通过创建用作工具提示的报表页,使自定义工具提示包含视觉对象.图像以及在 ...

  7. 挑战中英实时语音翻译——Skype Translator 中文预览版登陆中国

    Translator 中文预览版登陆中国" title="挑战中英实时语音翻译--Skype Translator 中文预览版登陆中国"> 今天,我们正式宣布在中国 ...

  8. 【译】.NET 7 预览版 1 中的 ASP.NET Core 更新

    原文 | Daniel Roth 翻译 | 郑子铭 .NET 7 预览版 1 现已推出!这是 .NET 下一个主要版本的第一个预览版,其中将包括使用 ASP.NET Core 进行 Web 开发的下一 ...

  9. .NET 7 预览版2 中的 ASP.NET Core 更新

    .NET 7 预览版2 现已推出,其中包括对ASP.NET Core 的许多重大改进. 以下是此预览版中新增内容的摘要: 推断来自服务的API 控制器操作参数 SignalR 集线器方法的依赖注入 为 ...

随机推荐

  1. VPS,虚拟主机,云主机,独立服务器区别

    作者:张朝权链接:http://www.zhihu.com/question/25507629/answer/105594087来源:知乎著作权归作者所有,转载请联系作者获得授权.   独立服务器独立 ...

  2. DTO学习系列之AutoMapper(一)

    一.前言 DTO(Data Transfer Object)数据传输对象,注意关键字“数据”两个字,并不是对象传输对象(Object Transfer Object),所以只是传输数据,并不包含领域业 ...

  3. HTML解析利器 - HtmlAgilityPack

    HtmlAgilityPack 是CodePlex 上的一个开源项目.它提供了标准的DOM API 和XPath 导航--即使 HTML 不是适当的格式! 使用HtmlAgilityPack操作HTM ...

  4. JS常用的方法

    1.时间戳转换 //时间戳(有Date和无Date的都可)转换为日期 “2016年5月30日 10:29:30 2016-05-20 09:11” function TimeConversion(ti ...

  5. nodejs 保存 payload 发送过来的文件

    1:接受文件 http://stackoverflow.com/questions/24610996/how-to-get-uploaded-file-in-node-js-express-app-u ...

  6. 织梦dedecms5.7后台进去就卡死解决方法

    症状:进入dede后台点击菜单后,浏览器进入假死状态要等好久才能反应过来. 解决方式:1.打开后台目录dede/templets/ 2.找到index_body.htm文件中的第25行至第35行部分屏 ...

  7. 更快的方式实现PHP数组去重(转)

    概述 使用PHP的array_unique()函数允许你传递一个数组,然后移除重复的值,返回一个拥有唯一值的数组.这个函数大多数情况下都能工作得很好.但是,如果你尝试在一个大的数组里使用array_u ...

  8. WordPress插件制作教程(四): 将数据保存到数据库

    上一篇讲解了添加菜单的方法,这一篇为大家讲解如何将数据保存到数据库中,并且显示在页面上,不会因提交表单时刷新页面输入框中内容消失.要实现这一功能我们需要借助WordPress函数来实现,下面就来讲解具 ...

  9. 阅读书目_2014H1

    1.<程序员修炼之道 专业程序员必知的33个技巧>(完成) 注:更多是面向程序员全工作流程的. 2.linux shell脚本攻略 适合初学,但不方便作为参考手册查阅. 3.编写可读代码的 ...

  10. hadoop集群之HDFS和YARN启动和停止命令

    假如我们只有3台linux虚拟机,主机名分别为hadoop01.hadoop02和hadoop03,在这3台机器上,hadoop集群的部署情况如下: hadoop01:1个namenode,1个dat ...