C#6.0新特性

一、字符串插值

 class Program
    {
        static void Main(string[] args)
        {
            //c#6.0新特性:字符串插值
            var name = "Jack";
            Console.WriteLine($"Hello {name}");//结果为:Hello Jack

            Person p = new Person() { FirstName = "Jack", LastName = "Wang", Age = 68 };
            //以下结果等价于:var results = string.Format("First Name: {0} LastName: {1} Age: { 2} ", p.FirstName, p.LastName, p.Age);
            var result = $"First Name:{p.FirstName} Last Name:{p.LastName}  Age:{p.Age}";

            //字符串插值不光是可以插简单的字符串,还可以直接插入代码
            Console.WriteLine($"Jack is saying {Program.SayHello()}");//结果为:Jack is saying Hello
            var info = $"Your discount is {await GetDiscount()}";
            ReadLine();
        }

        public static string SayHello()
        {
            return "Hello";
        }
    }

二、空操作符 ( ?. )

?. 操作符,当一个对象或者属性职为空时直接返回null, 就不再继续执行后面的代码

if (user != null && user.Project != null && user.Project.Tasks != null && user.Project.Tasks.Count > 0)
 {
   Console.WriteLine(user.Project.Tasks.First().Name);
 }

现在我们可以不用写 IF 直接写成如下这样:

Console.WriteLine(user?.Project?.Tasks?.First()?.Name);

这个?. 特性不光是可以用于取值,也可以用于方法调用

 class Program
{
    static void Main(string[] args)
    {
        User user = null;
        user?.SayHello();
        Console.Read();
    }
}

public class User
{
    public void SayHello()
    {
        Console.WriteLine("Ha Ha");
    }
}

还可以用于数组的索引器

class Program
{
    static void Main(string[] args)
    {
        User[] users = null;

        List<User> listUsers = null;

        // Console.WriteLine(users[1]?.Name); // 报错
        // Console.WriteLine(listUsers[1]?.Name); //报错

        Console.WriteLine(users?[1].Name); // 正常
        Console.WriteLine(listUsers?[1].Name); // 正常

        Console.ReadLine();
    }
}

注意: 上面的代码虽然可以让我们少些很多代码,而且也减少了空异常,但是我们却需要小心使用,因为有的时候我们确实是需要抛出空异常,那么使用这个特性反而隐藏了Bug

三、 NameOf

过去,我们有很多的地方需要些硬字符串,比如

if (role == "admin")
{
}

public string Name
{
  get { return name; }
  set
  {
      name= value;
      RaisePropertyChanged("Name");
  }
}

现在有了C#6 NameOf后,我们可以这样

public string Name
{
  get { return name; }
  set
  {
      name= value;
      RaisePropertyChanged(NameOf(Name));
  }
}

  static void Main(string[] args)
    {
        Console.WriteLine(nameof(User.Name)); //  output: Name
        Console.WriteLine(nameof(System.Linq)); // output: Linq
        Console.WriteLine(nameof(List<User>)); // output: List
        Console.ReadLine();
    }

注意: NameOf只会返回Member的字符串,如果前面有对象或者命名空间,NameOf只会返回 . 的最后一部分, 另外NameOf有很多情况是不支持的,比如方法,关键字,对象的实例以及字符串和表达式

四、在Catch和Finally里使用Await

之前的版本里,C#开发团队认为在Catch和Finally里使用Await是不可能,而现在他们在C#6里实现了它

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

五、表达式方法体

一句话的方法体可以直接写成箭头函数,而不再需要大括号

 public class Programe1
    {
        public static string SayHello() => "Hello world";

        public static string JackSayHello() => $"Jack {SayHello()}";

        static void Main()
        {
            Console.WriteLine(SayHello());
            Console.WriteLine(JackSayHello());
            Console.Read();
        }
    }

六、属性初始化器

之前我们需要赋初始化值,一般是在构造函数赋值,现在可以这样

public class Person
{
    public int Age { get; set; } = 100;
}

七、异常过滤器 Exception Filter

          try
            {
                throw new ArgumentException("Age");
            }
            catch(ArgumentException a) when (a.Message.Equals("Age"))
            {
                throw new ArgumentException("Name Exception");
            }
            catch(ArgumentException arg) when(arg.Message.Equals("Age"))
            {
                throw new ArgumentException("not handle");
            }
            catch (Exception e)
            {
                throw e;
            }        

之前,一种异常只能被Catch一次,现在有了Filter后可以对相同的异常进行过滤

八、 Index 初始化器

这个主要是用在Dictionary上

var names = new Dictionary<int, string>
            {
                [0] = "jack",
                [1] = "Kimi",
                [2] = "Jason",
                [3] = "Lucy"
            }
foreach (var item in names)
     {
           Console.WriteLine($"{item.Key}={item.Value}");
     }     

九、using 静态类的方法可以使用 using static

namespace ConsoleTest
{
    using static System.Console;
    public class Programe1
    {
        static void Main()
        {
            WriteLine("Hello world");
            ReadLine();
        }
    }
}

作者: 王德水

出处:http://www.cnblogs.com/cnblogsfans/p/5086292.html

版权:本文版权归作者所有,转载需经作者同意。