Visual Studio 2015与C#6.0新特性

原文链接:http://www.xcode.me/more/visual-studio-2015-new-features

1、使用null条件运算符,在调用对象的属性或者方法时,我们通常需要检查对象是否为null,现在你不需要写一个if语句,我们提供更便捷的方法,下面的代码获取list中元素的数量,当list本身为null时,Count方法也将返回null值。

public int? GetListItemCount(List<int> list)
{
    return list?.Count();
}

2、使用新增的nameof关键字获取参数、成员和类型的字符串名称。比个例子:当需要知道变量名的字符串表示形式时,我们可以这样写:

DateTime currentDate = DateTime.Now;
Console.WriteLine("{0}={1}", nameof(currentDate), currentDate);

输入结果如下所示,nameof关键字将变量名作为字符串形式直接输出:

currentDate=2014/12/8 21:39:53

3、在字符串中直接插入变量,而不需要在字符串格式化语句中写形如{n}的格式化模板,如下的代码输出:“零度编程,欢迎您!”

string siteName = "零度编程";
string welcome = "{siteName},欢迎您!";

4、Lambda表达式可以作为方法体或者属性的实现,我们可以直接将一个表达式赋予一个方法或者属性。

public class Book
{
    public decimal Price { get; set; }

    public int Count { get; set; }

    public decimal GetTotalPrice() => this.Price * this.Count;
}
public class Book
{
    public decimal Price { get; set; }

    public int Count { get; set; }

    public decimal TotalPrice => this.Price * this.Count;
}

5、在这之前,如果您要初始化对象的一个属性或者给属性赋默认值,需要定义一个私有字段,给私有字段赋初始值,现在可以这样写:

public class Book
{
    public decimal Price { get; set; } = 0m;

    public int Count { get; set; } = 10; 
}

6、在新的C#6.0种提供了对象索引初始化的新方法,现在初始化一个对象的索引可以这样:

var myObject = new MyObject
{
    ["Name001"] = "零度",
    ["Name002"] = "编程",
    ["Name003"] = "网站"
};

7、在对一个异常进行catch捕获时,提供一个筛选器用于筛选特定的异常,这里的if就是一个筛选器,示例代码如下:

try
{
    throw new ArgumentNullException("bookName");
}
catch (ArgumentNullException e) if(e.ParamName == "bookName")
{
    Console.WriteLine("bookName is null !");
}

8、静态引用,在这之前通过using关键字可引用命名空间,现在你可以通过using引用一个类,通过using引用的类,在代码中可不写类名,直接访问静态属性和方法。

using System.IO.File;

namespace Test
{
    public class MyClass
    {
        public void CreateTextFile(string fileName)
        {
            CreateText(fileName);
        }
    }
}

上面代码中CreateText属于System.IO命名空间下File静态类的方法,由于我们使用了using静态引入了类File,所以可直接使用方法名,而不需要File.CreateText(fileName)这样写。

9、这是另一个和异常相关的特性,使得我们可以在catch 和finally中等待异步方法,看微软的示例:

try
{
  res = await Resource.OpenAsync(“myLocation”); // You could do this.
}
catch (ResourceException e)
{
  await Resource.LogAsync(res, e); // Now you can do this. 
} 
finally
{
  if (res != null)
  await res.CloseAsync(); // … and this. 
}

10、在之前,结构struct不允许写一个无参构造函数,现在您可以给结构写一个无参构造函数,当通过new创建结构时构造函数会被调用,而通过default获取结构时不调用构造函数。

11、使用Visual Studio 2015 创建项目时,不但可选择.NET Framework的版本,现在也可选择C#语言的版本。

12、对字典的初始化,提供新的方法,在新版本的C#6中可使用如下的方式初始化一个字典。

Dictionary<string, string> siteInfos = new Dictionary<string, string>()
{
    { "SiteUrl", "www.xcode.me" },
    { "SiteName", "零度编程" },
    { "SiteDate", "2013-12-09" }
};

13、新的代码编辑器提供更好的体验,集成最新名为Roslyn的编译器,一些新的特性让您对这款编辑器爱不释手,最新的Visual Studio 2015中新增了一个灯泡功能,当您的代码中存在需要修复的问题或者需要重构时,代码行的左边将显示一个小灯泡,点击小灯泡后编辑器将帮助您自动修复和重构现有代码。

原文地址:https://www.cnblogs.com/FH-cnblogs/p/4668388.html