Alotus  

 https://docs.microsoft.com/zh-tw/dotnet/csharp/whats-new/csharp-version-history

 

C# 6

1. Null 条件运算符

var first = person?.FirstName;  
如果 Person 对象是 null,则将变量 first 赋值为 null否则,将 FirstName 属性的值分配给该变量。 最重要的是,?. 意味着当 person 变量为 null 时,此行代码不会生成 NullReferenceException它会短路并返回 null还可以将 null 条件运算符用于数组或索引器访问。 将索引表达式中的 [] 替换为 ?[]
var first = person?.FirstName?.ToString()

2.字符串内插
public string FullName => $"{FirstName} {LastName}";

3.异常筛选器
catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("301")) 如果表达式计算结果为 false,则将跳过 catch 子句

4.nameof 表达式
if (IsNullOrWhiteSpace(lastName)) throw new ArgumentException(message: "Cannot be blank", paramName: nameof(lastName));

5.使用索引器初始化关联集合
Dictionary<int, string> webErrors = new Dictionary<int, string>
{
    [404] = "Page not Found",
    [302] = "Page moved, but left a forwarding address.",
    [500] = "The web server can't come out to play today."
};
string str = webErrors[500];

C#  7.0

https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-7#out-variables

 

1.out 变量新语法。类似for循环中定义变量

if (int.TryParse(input, out int result)) Console.WriteLine(result);

 

2. 元组

(string Alpha, string Beta) namedLetters = ("a", "b");

Console.WriteLine($"{namedLetters.Alpha}, {namedLetters.Beta}");

 

var alphabetStart = (Alpha: "a", Beta: "b");

Console.WriteLine($"{alphabetStart.Alpha}, {alphabetStart.Beta}");

 

(int max, int min) = Range(numbers);

public class Point
   {
       public Point(double x, double y)
           => (X, Y) = (x, y);

       public double X { get; }
       public double Y { get; }

       public void Deconstruct(out double x, out double y) =>
           (x, y) = (X, Y);
   }
var p = new Point(3.14, 2.71);
(double X, double Y) = p;

3. 弃元 弃元是一个名为 _(下划线字符)的只写变量,可向单个变量赋予要放弃的所有值。
var (_, _, _, pop1, _, pop2) = QueryCityDataForYears("New York City", 1960, 2010);
 4. 数字文本语法改进。引入 _ 作为数字分隔符
public const int Sixteen =   0b0001_0000;
public const long BillionsAndBillions = 100_000_000_000;

 C# 7.1

https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-7-1

1. 异步 main 方法

static async Task<int> Main()
{
    // This could also be replaced with the body
    // DoAsyncWork, including its await expressions:
    return await DoAsyncWork();
}

2. 推断元组元素名称

int count = 5;
string label = "Colors used in the map";
var pair = (count: count, label: label);  //C#7.0
var pair = (count, label); // element names are "count" and "label"   C#7.1

 

 

 


 
 
posted on 2019-08-08 19:34  Alotus0  阅读(115)  评论(0)    收藏  举报