C# 6.0 新特性收集

先来看一段Json.Net的代码
public JObject ToJson()
        {
            var result = new JObject();
            result["X"] = X;
            result["Y"] = Y;
            return result;
        }

改进后的代码可以这么写

复制代码
public JObject ToJson()
        {
            var result = new JObject()
            {
                ["X"] = X,
                ["Y"] = Y
            };
            return result;
        }

最终可以化简成一行代码

public JObject ToJson() => new JObject() { ["X"] = X, ["Y"] = Y };
 
 
 
1. 静态using(static using)
 

1. 静态using(static using)

静态using声明允许不使用类名直接调用静态方法
 
C# 5
using System; 
Console.WriteLine("Hello, World!");
 
usingstatic System.Console;
WriteLine("Hello, World");
 
2. 表达式方法(Expression-Bodied Methods)
 
In C# 5
public bool IsSquare(Rectangle rect)
{
return rect.Height == rect.Width;
}
In C# 6
public bool IsSquare(Rectangle rect) => rect.Height == rect.Width;

1. 方法(Methods)

1   public Student Create() => new Student();

 等同于:

1   public Student Create()
2   {
3returnnew Student();
4   }

 2. 只读属性(read only properties)

1   publicstring FullName => string.Format("{0},{1}", FirstName, LastName);

 等同于:

 
1   publicstring FullName
2   {
3get4       {
5returnstring.Format("{0},{1}", FirstName, LastName);
6       }
7   }
 

原理解析:上面的表达式在编译后会生成最原始的方法体和访问器,值得一提的是函数表达式体跟Lambda是两个相似但不相同的东西,函数的表

达式体只能带一句话且不能包含return关键字但Lambda 能带语句块和包含关键字。

public Point Move(int dx, int dy) => new Point(x + dx, y + dy);  

再来举一个简单的例子:一个没有返回值的函数

publicvoid Print() => Console.WriteLine(FirstName + " " + LastName);
 
 
3. 表达式属性(Expression-Bodied Properties)
 
跟表达式方法类似,只有一个get访问器的单行属性可以使用lambda语法写。
publicstring FullName { get { return FirstName +"" + LastName; } }
publicstring FullName => FirstName +"" + LastName;
 
用C#6的这个新特性,代码就会大大减小,而且可读性比起之前大大增强
 
 
4. 自动属性初始化器(Auto-Implemented Property Intializers)
 

In C# 5

publicclassPerson
{
    publicPerson()
    {
        Age = 24;
    }
    publicint Age {get; set;}
}
 

In C# 6

publicclassPerson
{
    publicint Age {get; set;} = 42;
}
 
 
 
 
5. 只读自动属性(Read-Only Auto Properties)
 

In C# 5

privatereadonlyint _bookId;
public BookId
{
    get
    {
        return _bookId;
    }
}

In C# 6

publicBookId {get;}
 
 
 
6. nameof操作符(nameof Operator)
字段、属性、方法和类型的name可以通过nameof访问。使用nameof,可以方便的重构name变化。

In C# 5

publicvoidMethod(object o)
{
    if (o == null) thrownew ArgumentNullException("o");
}

In C# 6

publicvoidMethod(object o)
{
    if (o == null) thrownew ArgumentNullException(nameof(o));
}
  1. public class MyClass  
  2. {  
  3.     [TestMethod]  
  4.     public static void Show(int age)  
  5.     {  
  6.         Console.WriteLine(nameof(MyClass)); // 输出 MyClass 类名  
  7.     Console.WriteLine(nameof(Show)); // 输出 Show 方法名  
  8.     Console.WriteLine(nameof(age)); // 输出 age  
  9.     Console.WriteLine(nameof(TestMethodAttribute)) // 输出 Attribute 名  
  10.     }  
  11. }
 
 
7. Null传递操作符(Null Propagation Operator)
 
int? age = p == null ? null : p.Age;
var handler = Event;
if (handler != null)
{
    handler(source, e);
}

In C# 6

int? age = p?.Age;
handler?.Invoke(source, e);
 
8. 字符串插值(String Interpolation)
 
 
C# 6之前我们拼接字符串时需要这样
 
var Name = "Jack";
var results = "Hello" + Name;
或者
 var Name = "Jack";
 var results = string.Format("Hello {0}", Name);
WriteLine(($"{Name }"))
 
9. 字典初始化器(Dictionary Initializers)
 

In C# 5

var dict = new Dictionary<int, string>();
dict.Add(3,"three");
dict.Add(7,"seven");

In C# 6

var dict = new Dictionary<int, string>()
{
    [3] ="three",
    [7] ="seven"
};
 
10. 异常过滤器(Exception Filters)
 

In C# 5

try
{
    //etc.
} catch (MyException ex)
{
    if (ex.ErrorCode != 405) throw;
    // etc.
}

In C# 6

try
{
    //etc.
} catch (MyException ex) when (ex.ErrorCode == 405)
{
    // etc.
}
 
11. 在Catch使用Await(Await in Catch)
 
bool hasError = false;
string errorMessage = null;
try
{
    //etc.
} catch (MyException ex)
{
    hasError = true;
    errorMessage = ex.Message;
} 
if (hasError)
{
    awaitnew MessageDialog().ShowAsync(errorMessage);
}

In C# 6

try
{
    //etc.
} catch (MyException ex)
{
    awaitnew MessageDialog().ShowAsync(ex.Message);
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/zhangruiBlog/p/8034387.html