导航

C#6.0新语法

Posted on 2018-04-02 01:01  清浅ヾ  阅读(255)  评论(0编辑  收藏  举报
1.自动属性初始化的改进(有用)

原来的用法(声明时无法同时初始化),例如:
class MyClass
{
  public int Age { get; set; }
  public string Name { get; set; }
  public MyClass()
  {
    Age = 20;
    Name = "张三";
  }
} 

新用法(声明时可同时初始化,更方便了),例如:
class MyClass
{
  public int Age { get; set; } = 20;
  public string Name { get; set; } = "张三";
} 

2.String.Format的改进(有用)

原来的用法:用string.Format(…)实现,例如:
class MyClass
{
  public void MyMethod()
  {
    string name = "张三";
    int age = 20;
    string s1 = string.Format("{0},{1}", name, age);
    string s2 = string.Format("姓名={0},年龄={1}", name, age);
    string s3 = string.Format("{0,15},{1:d3}", name, age);
    string s4 = string.Format("{0,15},{1,10:d3}", name, age);
    Console.WriteLine("{0},{1},{2},{3}", s1, s2, s3 ,s4);
    string s5 = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
  }
}

新用法:用“$”前缀实现(变量直接写到大括号内,而且带智能提示,更方便了),例如:
class MyClass
{
  public void MyMethod()
  {
    string name = "张三";
    int age = 20;
    string s1 = $"{name},{age}";
    string s2 = $"姓名={name},年龄={age}";
    string s3 = $"{name,15},{age:d3}";
    string s4 = $"{name,15},{age,10:d3}";
    Console.WriteLine($"{s1},{s2},{s3},{s4}");
    string s5 = $"{DateTime.Now:yyyy-MM-dd}";
  }
} 

3、字典的初始化
原来的用法: 
class MyClass
{
  public void MyMethod()
  {
    Dictionary<string, int> student = new Dictionary<string, int>();
    student.Add("a1", 15);
    student.Add("a2", 14);
    student.Add("a3", 16);
  }
} 

新用法(可以直接写初始化的值,更方便了): 
class MyClass
{
  public void MyMethod()
  {
    Dictionary<string, int> student = new Dictionary<string, int>()
    {
      ["a1"] = 15,
      ["a2"] = 14,
      ["a3"] = 16
    };
  }
} 

4、可以用static声明静态类的引用

原来的用法: 
using System;
namespace MyApp
{
  class Demo1New
  {
    public static double MyMethod(double x, double angle)
    {
      return Math.Sin(x) + Math.Cos(angle);
    }
  }
} 

新用法(表达式比较复杂的时候有用,代码更简洁了):
using static System.Math;
namespace MyApp
{
  class Demo1New
  {
    public static double MyMethod(double x, double angle)
    {
      return Sin(x) + Cos(angle);
    }
  }
} 

5、nameof表达式

假定WPF应用程序中有下面的类: 
public class MyClass
{
     public string MyText { get; set; } = "aaa";
}

并假定有下面的XAML代码:
<StackPanel>
<TextBlock Name="txt1"/>
……
</StackPanel>

 代码隐藏类中原来的用法:
 txt1.SetBinding(TextBlock.TextProperty, "MyText"); 

现在的用法(因为有错误检查智能提示,用起来更方便了):
 txt1.SetBinding(TextBlock.TextProperty, nameof(MyClass.MyText)); 

6、Null-条件表达式

var ss = new string[] { "Foo", null };
var length0 = ss [0]?.Length; // 结果为3
var length1 = ss [1]?.Length; // 结果为null
var lengths = ss.Select (s => s?.Length ?? 0); //结果为[3, 0] 

7、在try-catch-finally中使用await

异步编程中,原来在catch或者finally中无法使用await,现在可以了:
async void SomeMethod()
{
  try
  {
    //...etc...
  }
  catch (Exception x)
  {
    var diagnosticData = await GenerateDiagnosticsAsync (x);
    Logger.log (diagnosticData);
  }
  finally
  {
    await someObject.FinalizeAsync();
  }
}