c#6.0 Exclusive assignment of new notes getter
You can assign an initial value to a property that has only get in the constructor.
Class point {public int x {get;} Public Point () { x = 1; } }
Automatic attribute Initialization
You can assign an initialization value to an automatic attribute.
Class point {public int x {get; set;} = 1; }
Global static
You can set global static, and then write directly to the method of the static class.
Using static system.console;namespace fxapp{ internal class program { private static void Main (String[] args) { Read (); }}}
Global enumeration
You can set the global enumeration and then write the enumeration properties directly
Using static system.consolecolor;namespace fxapp{ internal class program { private static void Main (String[] args) { var color = Red; }}}
String insertion
You can use $ for string insertions instead of String.Format. Global variables or parameters can be inserted
Internal class program {public static int x {get; set;} private static void Main (string[] args) { string text = $ "{X},{args}"; } }
Expression bodied
You can use an arrow expression to provide an expression body to a method or property. Note that the expression body cannot have parentheses.
Internal class program {public string Name = "Chenxy"; public int Sum (int x, int y) = + x + y; private static void Main (string[] args) {program PO = new program (); Console.WriteLine (PO. Name); Chenxy Console.WriteLine (PO. Sum (1, 2)); 3 Console.read (); } }
Index value Initialization
You can assign an initialization value to a collection
Internal class program { idictionary<int, string> dict = new Dictionary<int, string>() { [1] = "First", [2] = "Second" }; private static void Main (string[] args) {program PO = new program (); foreach (var item in Po.dic T) {Console.WriteLine (item. Value); } console.read (); } }
?. Operator
Null operator, which simplifies the work of judging null
public class point {public int x {get;} = 1; } Internal class program {public static void Main (string[] args) {point po = null; C # 5.0 notation if (PO! = null) {Console.WriteLine (po.x);}//c# 6.0 notation Console.WriteLine (po?. x); Console.read (); } }
nameof-expression
To prevent the refactoring from forgetting to modify, you can use nameof to bind a constant and a variable. Constants change when variables change
Internal class program {public static void Main (string[] args) { string error = string< c23>. Empty; C # 5.0 Console.WriteLine ("Error"),//error //c# 6.0 Console.WriteLine (nameof (Error));//error console.read (); } }
In this code, if the error name is changed, but the nameof (error) name is not modified. You will be prompted at compile time
Exception filter
You can judge in a try catch to control whether a catch is entered. If Hideerror is false, no catch is entered.
public static void Main (string[] args) { bool hideerror = False; Try { throw new Exception (); } Catch (Exception ex) when (Hideerror) { Console.WriteLine ("Exception has been thrown");} Console.read (); }
Use await in catch and finally
You can use await in catch and finally.
Internal class program {public async static void Main (string[] args) { HttpClient client = null ; Try { var result = await client. Getasync (""); } Catch (Exception ex) {var result = await client. Getasync ("");} Finally {var result = await client. Getasync ("");} Console.read (); } }
Visual Studio 2017
https://zhuanlan.zhihu.com/p/25626653
c#7.0 New Sex Note out
In the original code, if you use out parameters, you need to define the variables beforehand. In C#7, you can define variables directly in the output parameters.
We can also define the var implicit variable directly in the parameter.
vs2015static void Main (String[] args) { int x; Outmethod (out x); WriteLine ($ "x:{x}"); Read (); } vs2017static void Main (String[] args) { outmethod (out int x); WriteLine ($ "x:{x}"); Read (); }
Deconstruction
In the calling function, you can encapsulate a combination of parameters into a constructor of a class. However, it is not possible to construct individual components through object solutions.
By deconstructing the function, you can do it. The destructor can return the object's specific determination component.
For example, we simulate a combination of parameters
public class PathInfo {public string directoryname {get; set;} public string FileName {get; set;} public string Extension {get; set;} Public PathInfo (String dname, String fname, string extension) { directoryname = dname; FileName = fname; Extension = Extension;}}
We need to load system.valuetuple from NuGet so that we can use tuples to deconstruct.
If we want to use deconstruction, we need to first define a destructor: desconstruct
public void deconstruct (out string dname, out string fname, out string extension) { dname = directoryname; fname = FileName; Extension = extension; }
Note that you must use out, the name can be different, and he is returned in the order of the parameters.
Next, we now use the destructor to invoke. We show three examples to invoke the test.
Class program { static void Main (string[] args) { PathInfo info = new PathInfo ("D", "F", "E" ); Example one: declaration within a parameter. You can also use var (string dname, String fname, string extension) = info; WriteLine ($ "{dname},{fname},{extension}"); Example two: declaring value initialization. Assign an existing variable string dname1, fname1, extension1 = null; (Dname1, fname1, extension1) = info; WriteLine ($ "{dname1},{fname1},{extension1}");//Example three: implicit variable declaration var (dname2, fname2, extension2) = info; WriteLine ($ "{dname2},{fname2},{extension2}"); Read (); } }
Similar to tuples, each value is assigned a value, as long as the order corresponds.
Note: In the example three, we declare the Var outside the parentheses so that the three variable types within the parentheses must be identical.
A destructor that requires at least two output variables in parentheses. If only one is not working, for example
(string dname) = info; This is not going to work. Deconstruct, if there is only one method is not possible.
Deconstruct, which can be overloaded. When used, the corresponding overloaded method is automatically found.
Meta-group
Tuples allow you to return multiple values from one method. Before c#7.0, we define an output parameter or a collection of objects.
We can define the ancestors in two ways.
1. Do not use parameter names, only fill in parameter types. This will return item1,2,3
2. Use the parameter name and fill in the parameter type. This returns the item. Name of the parameter
3. Direct use of parameter names. and 21 effects, but a little easier.
Class program { static void Main (string[] args) { PathInfo info = new PathInfo (); var item = info.getempinfo (); WriteLine ($ "{Item. Item1},{item. Item2},{item. ITEM3} "); var item2 = Info.getempinfo2 (); WriteLine ($ "{item2.a},{item2.b},{item2.c}"); var item3 = Info.getempinfo3 (); WriteLine ($ "{item3.a},{item3.b},{item3.c}"); Read (); }} public class PathInfo {//does not use parameter names, returns item1,2,3 public (String, string, String) Getempinfo () {return ("a", "B "," C ");} Using the parameter name, return the definition Parameter name public (string A, string B, String c) GetEmpInfo2 () {return ("a", "B", "C");}//Use the specified element publi C (String A, string B, String c) GetEmpInfo3 () {return (A: "A", B: "B", C: "C");}}
Pattern matching
Sometimes a base class derives some subclasses. If we want to implement the eject method for each class. You can use multiple choices to implement.
As operator
converting and assigning values using the AS operator
Check whether the result is null
Performing Eject operations
Is operator
Checking types with the IS operator
Convert type and assign value to it
Performing Eject operations
Cast
Show Conversion Assignment
Catching a possible exception
Perform actions
The problem with these methods is that the syntax is rather lengthy, and that you always provide multiple statements for the converted Class
Pattern matching with IS expression
c#7.0 provides pattern matching, which is used as a way to combine tests and assignments into a single action method.
For example, before c#7, the type conversions are as follows. We use the IS operator
Class program { static void Main (string[] args) { Eject (new Woman ()); Read (); } static void Eject (people peo) { if (PEO is Woman) { Woman wo = (Woman) peo; wo. Con (); }}} class people {} class woman:people {public void Con () {WriteLine ("This is Woman");}}
As you can see, we need to do is and then convert. Now we use pattern matching to implement the above code
static void Eject (people peo) { if (peo is Woman wo) { wo. Con (); } }
Pattern matching combines tests and assignments into one operation.
Pattern matching for switch statements
Using switch can be more important between multiple compatible types that can be converted.
If we want to add an additional condition, you can use when to attach the case clause.
static void Eject (people peo) { switch (PEO) {case Woman wo when wo! = null: wo. Con (); Break; Case People PE: break; default: Break;}}
Local functions
c#7.0 allows full declaration of local functions within a member. To replace action and Func.
The local function acts on the field and is inside the surrounding function. Here are a few points to note about local functions
1. Modifiers are not allowed
2. Overloading is not supported
3. Local functions can access all variables, including local variables
4. The local function exists in the entire method scope, the declaration does not divide before and after
BOOL Ispalindrome (string text) { if (string. Isnullorwhitespace (text)) return false; BOOL Localispalindrome (string target) { target = target. Trim (); Start by removing any surrounding whitespace. if (target. Length <= 1) return true; else { return char. ToLower (target[0]) = = char. ToLower (Target[target. LENGTH-1]) && localispalindrome (target. Substring (1, Target. Length-2)); }} return localispalindrome (text);}
Return by reference
You can pass parameters to the function to update by using ref.
c#7.0 In addition to the ref parameter, you can return a reference through a function.
Class program { static void Main (string[] args) { int[] result = {1, 2, 3 }; ref int A = ref Find (result); A + = 1; WriteLine (result[0]); Read (); } static ref int Find (int[] sum) {return ref sum[0];}}
Text improvements
c#7.0 can be underlined to improve readability. Can be placed anywhere in the binary, decimal, hexadecimal digits
Long largestsquarenumberusingalldigits = 0b0010_0100_1000_1111_0110_1101_1100_0010_0100; 9,814,072,356long MaxInt64 {get;} = 9_223_372_036_854_775_807; Equivalent to Long. MaxValue
Throw-expression
You can throw an exception directly in an expression
public string Getempinfo (String empname) { string[] Emparr = Empname.split (","); Return (emparr.length > 0)? Emparr[0]: Throw new Exception ("Emp Info not Exist"); }
Asynchronous return type
The compiler does not restrict async methods from having to return void, Task, task<t>.
Any that can inherit the Getawaiter method can be returned.
However, this method I verify does not pass. Therefore, this feature is not considered for the time being.
Expression bodied Enhanced
c#7.0 inside the arrow function expression, has been enhanced.
We can use it directly in constructors, destructors,
public class Point {public point () = WriteLine ("construct"); ~point () = WriteLine ("release"); }
$
C # new feature record