As a language for Cheng (yu) (FA) (Tang), feel the full malice from Microsoft ...
1. String inline
In previous versions, the usual format strings were:
var s = String.Format("{0} is {1} year{{s}} old", p.Name, p.Age);
In C # 6:
//无格式var s = $"{p.Name} is {p.Age} year{{s}} old";//带格式var s = $"{p.Name,20} is {p.Age:D3} year{{s}} old";//带子表达式var s = $"{p.Name} is {p.Age} year{(p.Age == 1 ? "" : "s")} old";
2. Empty condition Operators
In previous versions, getting child elements was often more complex for nullable or dynamic types :
if(someSchool != null && someSchool.someGrade != null && someSchool.someGrade.someClass != null){ return someSchool.someGrade.someClass.someOne;}
In C # 6, a new operator is introduced:
return someSchool?.someGrade?.someClass?.someOne;//也可以使用下标运算,例如//return someArray?[0];
If?. operator returns NULL if the left entry is null.
For the execution of a method or delegate, you can use Invoke:
someMethod?.Invoke(args);
3. nameof expressions
You can directly return the name of the passed-in variable without complex reflection.
int someInt;Console.WriteLine(nameof(someInt)); //"someInt"
Note: If preceded by a namespace and/or class name, only the last variable name is returned.
4. Index initializer
The initialization method for Dictionary is simplified in C # 6:
var numbers = new Dictionary<int, string> { [7] = "seven", [9] = "nine", [13] = "thirteen" };
5. Conditional exception Handling
In C # 6, you can selectively process certain exceptions without adding additional judgment:
try { … } catch (MyException e) if (myfilter(e)) { … }
6. Property initializers
Properties can be initialized directly in C # 6:
public class Customer { public string First { get; set; } = "Jane"; public string Last { get; set; } = "Doe"; }
And can similarly define read-only properties.
7. Lambda definition of member functions
In C # 6, you can use a lambda expression to define a member method.
PublicClassPoint{PublicPointMove(IntDx,IntDy)=NewPoint(X+Dx,y + dy); public static complex operator + ( span class= "n" >complex acomplex b ) => a. Add (bpublic static implicit operator (person p) => $ "{P.first}, {p.last}" ;}
8. Parameter constructors for structural bodies
You can create a parametric constructor for a struct in C # 6.
structPerson{PublicStringName{Get;}PublicIntage {get} public person (string nameint age) { name = nameage = age} public person () : this ( "Jane Doe" 37 ) {} } /span>
9. Using static class
In C # 6, a using can be used in addition to a namespace for static classes.
using System.Console; using System.Math;class Program { static void Main() { WriteLine(Sqrt(3*3 + 4*4)); } }
From: http://www.zhihu.com/question/27421302
Feel the new grammar of c#6.0