C#
6.0 đi kèm với Visual Studio 2015, đối với Visual Studio thấp hơn có thể bạn cần nâng cấp Microsoft.Net.Compilers của mình. Mục tiêu của phiên bản này nhằm mang lại sự đơn giản. Nâng cao sự đơn giản của thao tác coding mà không cần biết các khái niệm rườm rà. Việc tăng cường tính năng mới sẽ làm cho C# tối ưu hơn nhưng không làm nó nặng hơn. Dưới đây là các tính năng mới trong C# 6.0:Auto-property enhancements↓
- Initializers for auto-properties↓
Expression-bodied function members↓
- Getter-only auto-properties↓
- Expression bodies on method-like members↓
Using static↓
- Expression bodies on property-like function members↓
Extension methods↓
Null-conditional operators↓
String interpolation↓
nameof expressions↓
Index initializers↓
Exception filters↓
Await in catch and finally blocks↓
The .NET Compiler Platform ("Roslyn")↓
Auto-property enhancements↑
A. Initializers for auto-properties↑
public string FirstName { get; set; } = "Jonh";
public string LastName { get; set; } = "Smith";
B. Getter-only auto-properties↑
public string FirstName { get; } = "Jonh";
public string LastName { get;} = "Smith";
Nếu chỉ có Getter thì lúc này field được mặc định định nghĩa là ReadOnly và chỉ được gán giá trị ở Constructors.
using System;
namespace CSharp6._0FeaturesDemo
{
public class Person
{
public string FirstName { get; } = "Jonh";
public string LastName { get; set; } = "Smith";
public Person()
{
//Default
}
public Person(string firstname, string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}
}
class Program
{
static void Main(string[] args)
{
/*P*/
var p = new Person();
Console.WriteLine("{0} {1}", p.FirstName, p.LastName);
//p.FirstName = "Bravo"; //=>Error
p.LastName = "Hex"; //=> Okay
Console.WriteLine("{0} {1}", p.FirstName, p.LastName);
/*P1*/
var p1 = new Person("Bravo","Hex");
Console.WriteLine("{0} {1}",p1.FirstName,p1.LastName);
Console.ReadLine();
}
}
}
Expression-bodied function members↑
Biểu thức Lambda có thể được khai báo với một biểu thức có body tương tự body của hàm thông thường chứa một block. Bạn có thể xem qua các ví dụ dưới đây để hiểu rõ hơn:A. Expression bodies on method-like members↑
Biểu thức bản chất là phương thức nhưng bạn có thể định nghĩa nó trông giống như propertiespublic static implicit operator string(Person p) => p.FirstName + " " + p.LastName;
public static Person operator +(Person a, Person b) => a.Add(b);
public void Show() => Console.WriteLine(FirstName + " " + LastName);
public static Person NewPerson(string firstname, string lastname) => new Person("Bravo", "Hex");
Ví dụ đầy đủ dưới đây sẽ cho bạn cái nhìn rõ hơn:
using System;
using System.Collections.Generic;
namespace CSharp6._0FeaturesDemo
{
public class Person
{
public string FirstName { get; set; } = "Jonh";
public string LastName { get; set; } = "Smith";
public Person()
{
//Default
}
public Person(string firstname, string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}
public static implicit operator string(Person p) => p.FirstName + " " + p.LastName;
public static List<Person> operator +(Person a, Person b) => a.Add(a, b);
public void Show() => Console.WriteLine(FirstName + " " + LastName);
public List<Person> Add(Person p1, Person p2)
{
///TODO: Something here!
return new List<Person>()
{
p1,
p2
};
}
}
class Program
{
public static Person NewPerson(string firstname, string lastname) => new Person("Bravo", "Hex");
static void Main(string[] args)
{
/*P*/
Console.WriteLine("========P========");
var p = new Person();
Console.WriteLine(p);
p.Show();
/*P1*/
Console.WriteLine("========P1========");
var p1 = NewPerson("Bravo", "Hex");
Console.WriteLine("{0} {1}", p1.FirstName, p1.LastName);
/*P2*/
Console.WriteLine("========P2========");
var persons = p + p1;
foreach (var item in persons)
{
Console.WriteLine("{0} {1}", item.FirstName, item.LastName);
}
Console.ReadLine();
}
}
}
//========P========
//Jonh Smith
//Jonh Smith
//========P1========
//Bravo Hex
//========P2========
//Jonh Smith
//Bravo Hex
B. Expression bodies on property-like function members↑
Properties and indexers có thể có getters and setters. Body của biểu thức có thể được sử dụng để thay thế thuộc tính getter-only và indexers.public string FullName => FirstName + " " + LastName;Xem ví dụ đầy đủ dưới đây:
public Person this[int id] => GetPerson(id);
using System;
namespace CSharp6._0FeaturesDemo
{
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; } = "Jonh";
public string LastName { get; set; } = "Smith";
public string FullName => FirstName + " " + LastName;
public Person this[int id] => GetPerson(id);
public Person()
{
//Default
}
public Person(int id, string firstname, string lastname)
{
this.Id = id;
this.FirstName = firstname;
this.LastName = lastname;
}
public Person GetPerson(int id)
{
if (id == this.Id)
return this;
return null;
}
}
class Program
{
static void Main(string[] args)
{
/*P*/
Console.WriteLine("========P========");
var p = new Person(1, "Bravo", "Hex");
Console.WriteLine("{0} {1}", p.Id, p.FullName);
var resut = p.GetPerson(1);
if(resut!=null)
Console.WriteLine("{0} {1}",p.Id, p.FullName);
Console.ReadLine();
}
}
}
//========P========
//1 Bravo Hex
//1 Bravo Hex
Using Static↑
Tính năng này cho phép bạn truy cập tất cả static member của đối tượng được imported. Bạn có thể dễ dàng sử dụng mà không cần gọi theo kiểu trước đây. Xem ví dụ để hiểu rõ hơn:using static System.Console;
namespace CSharp6._0FeaturesDemo
{
using static Person;
class Program
{
static void Main(string[] args)
{
WriteLine("Hello World!");
Show();
ReadLine();
}
}
static class Person
{
public static void Show()
{
WriteLine("Welcome to BravoHex!");
}
}
}
Extension methods↑
Mặc dù so sánh với cách sử dụng Extentsion methods ban đầu có vẻ không khác là mấy. Nhưng Sử dụng kết hợp với Using Static mang lại nhiều thuận tiện hơn. Xem ví dụ dưới đâyusing static System.Console;
namespace CSharp6._0FeaturesDemo
{
using static Person;
class Program
{
static void Main(string[] args)
{
SetAge(26).Show("BravoHex");
26.Show("BravoHex");
ReadLine();
}
}
static class Person
{
public static int SetAge(int age)
{
return age;
}
public static void Show(this int age, string fullname) //extension method of Int type
{
WriteLine("{0} is {1} year old!",fullname, age);
}
}
}
Null-conditional operators↑
cho phép truy vào members and elements khi đối tượng không null. Điều này giống như dạng validate sẵn cho bạn.List<Person> persons= new List<Person>()
{
new Person(1,"Jonh Smith"),
new Person(2,"Cassandra Barlow"),
new Person(3,"Megan Mccarthy"),
new Person(4,"Cherokee Martinez"),
new Person(5,"Zenia Huffman"),
};
int count = persons.Count; //Normal if person not null
int? count1 = null; //Allow nullable
int count2 = persons?.Count; //Error: Cannot implicitly convert type 'int?' to 'int'
int? count3 = persons1.Count; //Error: Object reference not set to an instance of an object.
int? count4 = persons?.Count; // Null if person null
//Essentially equivalent
int? count4a = (persons != null) ? persons.Count: new int?(); //Another option is (int?)null
int count5 = persons?.Count ?? 0; //Return 0 if person is null
//Essentially equivalent
int count5 = (persons!=null)?persons.Count:0;
String interpolation↑
Cho phép sử dụng biểu thức trong định dạng chuỗi làm mọi thứ dễ dàng hơn rất nhiều:var p = new Person(1, "Bravo Hex");
var s = string.Format("Id: {0} - Name: {1}", p.Id, p.FullName);
var s1 = $"Id: {p.Id} - Name: {p.FullName}";
var s2 = $"Id: {(p.Id == 1 ? "First" : "seconds")} - Name: {p.FullName}";
WriteLine($"{s}\n{s1}\n{s2}");
ReadLine();
//Id: 1 - Name: Bravo Hex
//Id: 1 - Name: Bravo Hex
//Id: First - Name: Bravo Hex
nameof expressions↑
Lấy tên của đối tượng hoặc thành viên được định nghĩa.WriteLine("Class: {0} \nMethod: {1}", nameof(Console), nameof(Console.WriteLine));
ReadLine();
//Class: Console
//Method: WriteLine
Index initializers↑
Cú pháp mới cho phép bạn set Key và Value với bất cứ indexer nào. Xem thêm ví dụ:var numbers = new Dictionary
{
[1] = new Person(1, "Jonh Smith"),
[3] = new Person(2, "Cassandra Barlow"),
[5] = new Person(3, "Megan Mccarthy"),
[7] = new Person(4, "Cherokee Martinez"),
[9] = new Person(5, "Zenia Huffman"),
};
foreach (var item in numbers)
{
WriteLine($"{item.Key} : {item.Value.FullName}");
}
ReadLine();
//1 : Jonh Smith
//3 : Cassandra Barlow
//5 : Megan Mccarthy
//7 : Cherokee Martinez
//9 : Zenia Huffman
Exception filters↑
Bổ sung điều kiện thực thi cho Cacthtry
{
///TODO: Something here!
}
catch (Exception) when(true)
{
///TODO: Something here!
throw;
}
Await in catch and finally blocks↑
Từ phiên bản này, await có thể sử dụng trong catch và finnal blocksResource res = null;Việc thực hiện được điều này khá là phức tạp, nhưng bây giờ nó đã được tích hợp. Bạn chỉ việc sử dụng.
try
{
res = await Resource.OpenAsync(…); // You could do this.
…
}
catch(ResourceException e)
{
await Resource.LogAsync(res, e); // Now you can do this …
}
finally
{
if (res != null) await res.CloseAsync(); // … and this.
}
Trình biên dịch Roslyn↑
.NET Compiler Platform ("Roslyn") là trình biên dịch C#/VB mã nguồn mở với các API phong phú. Bạn có thể tìm hiểu thêm tại GitHub ⇚References: MSDN, Github
Created: 26/11/2015
New Language Features in C# 6.0
Related Tags :C# C# 6.0 Features
No comments:
Post a Comment
Commets Download Photoshop Actions, Lightroom Presets, PSD Template, Mockups, Stocks, Vectors, Fonts. Download free