一小时学会C# 6?
一、字符串插值 (String Interpolation)?
C# 6之前我们拼接字符串时需要这样
var Name = "Jack";var results = "Hello" + Name;
var Name = "Jack";var results = string.Format("Hello {0}", Name);
var Name = "Jack";var results = $"Hello {Name}";
Person p = new Person {FirstName = "Jack", LastName = "Wang", Age = 100};var results = string.Format("First Name: {0} LastName: {1} Age: { 2} ", p.FirstName, p.LastName, p.Age);
var results = $"First Name: {p.FirstName} LastName: {p.LastName} Age: {p.Age}";
Console.WriteLine($"Jack is saying { new Tools().SayHello() }");var info = $"Your discount is {await GetDiscount()}";
Double remain = 2000.5; var results= $"your money is {remain:C}";
使用IFormattable 多语言
class Program
{static void Main(string[] args){Double remain = 2000.5; var results= ChineseText($"your money is {remain:C}");Console.WriteLine(results);Console.Read();}public static string ChineseText(IFormattable formattable){return formattable.ToString(null, new CultureInfo("zh-cn"));}
}
二、空操作符 ( ?. )?
C# 6添加了一个 ?. 操作符,当一个对象或者属性职为空时直接返回null, 就不再继续执行后面的代码,在之前我们的代码里经常出现 NullException, 所以我们就需要加很多Null的判断,比如
if (user != null && user.Project != null && user.Project.Tasks != null && user.Project.Tasks.Count > 0){Console.WriteLine(user.Project.Tasks.First().Name);}
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();}
}
三、 NameOf?
过去,我们有很多的地方需要些硬字符串,导致重构比较困难,而且一旦敲错字母很难察觉出来,比如
if (role == "admin")
{
}
public string Name
{get { return name; }set{name= value;RaisePropertyChanged("Name");}
}
public string Name
{get { return name; }set{name= value;RaisePropertyChanged(NameOf(Name));}
}
static void Main(string[] args)
{Console.WriteLine(nameof(User.Name)); // output: NameConsole.WriteLine(nameof(System.Linq)); // output: LinqConsole.WriteLine(nameof(List<User>)); // output: ListConsole.ReadLine();
}
四、在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.
}
五、表达式方法体?
一句话的方法体可以直接写成箭头函数,而不再需要大括号
class Program{private static string SayHello() => "Hello World";private static string JackSayHello() => $"Jack {SayHello()}";static void Main(string[] args){Console.WriteLine(SayHello());Console.WriteLine(JackSayHello());Console.ReadLine();}
}
六、自动属性初始化器?
之前我们需要赋初始化值,一般需要这样
public class Person
{public int Age { get; set; }public Person(){Age = 100;}
}
public class Person
{public int Age { get; set; } = 100;
}
七、只读自动属性?
C# 1里我们可以这样实现只读属性
public class Person
{private int age=100;public int Age{get { return age; }}
}
public class Person
{public int Age { get; private set; }}
public class Person
{public int Age { get; } = 100;
}
八、异常过滤器 Exception Filter?
static void Main(string[] args)
{try{throw new ArgumentException("Age");}catch (ArgumentException argumentException) when( argumentException.Message.Equals("Name")){throw new ArgumentException("Name Exception");}catch (ArgumentException argumentException) when( argumentException.Message.Equals("Age")){throw new Exception("not handle");}catch (Exception e){throw;}
}
九、 Index 初始化器?
这个主要是用在Dictionary上,至于有什么用,我目前没感觉到有一点用处,谁能知道很好的使用场景,欢迎补充:
var names = new Dictionary<int, string>
{[1] = "Jack",[2] = "Alex",[3] = "Eric",[4] = "Jo"
};foreach (var item in names)
{Console.WriteLine($"{item.Key} = {item.Value}");
}
十、using 静态类的方法可以使用 static using?
这个功能在我看来,同样是很没有用的功能,也为去掉前缀有的时候我们不知道这个是来自哪里的,而且如果有一个同名方法不知道具体用哪个,当然经证实是使用类本身的覆盖,但是容易搞混不是吗?
using System;
using static System.Math;
namespace CSharp6NewFeatures{class Program{static void Main(string[] args){Console.WriteLine(Log10(5)+PI);}}
}