1. 数字定义改进
int million = 1_000_000;
Console.WriteLine(million);

var binNum = 0b1001_0001;
Console.WriteLine(binNum);

image.png
2.输出变量及参数忽略

bool res = int.TryParse("123", out int result);
Console.WriteLine(res);

输出:
True
3.模式
is运算符,可以少一次转换

object a = 32;
if (a is int x)
{
    Console.WriteLine(x.ToString());
}

输出:
32

switch模式

object obj = 32;

switch (obj)
{
    case int i:
        Console.WriteLine("it's int!");
        break;
    case string s:
        Console.WriteLine("it's string");
        break;
    case null:
        Console.WriteLine("noting");
        break;
}

输出
it's int!
4.局部方法

WriteCubes();
void WriteCubes()
{
    Console.WriteLine(Cube(3));
    Console.WriteLine(Cube(4));
    Console.WriteLine(Cube(5));
    int Cube(int val)=> val*val*val;
}

输出:
`27
64
125`

3.更多的表达式体成员

 public class Person
 {
     string name;

     public Person(string name) => Name = name;

     public string Name
     {
         get => name; 
         set => name = value??"";
     }

     ~Person() => Console.WriteLine("finalize");
 }

5.解构器
在Person类中增加结构器

public void Deconstruct(out string firstName, out string lastName)
{
    int spacePos = name.IndexOf(' ');
    firstName = name.Substring(0, spacePos);
    lastName = name.Substring(spacePos + 1);
}

调用代码:

var joe = new Person("Joe Bidden");
var (first, last) = joe;
Console.WriteLine(first);
Console.WriteLine(last);

输出:
`Joe
Bidden`

6.元组

var bob = ("Bob", 23);
Console.WriteLine(bob.Item1);
Console.WriteLine(bob.Item2);

var tuple = (Name: "Bob", Age: 23);
Console.WriteLine(tuple.Name);
Console.WriteLine(tuple.Age);


(int row, int col) GetFilePos() => (3, 10);

var pos = GetFilePos();
Console.WriteLine(pos.row);
Console.WriteLine(pos.col);

输出:

Bob
23
Bob
23
3
10

6.null条件判断


Wittgenstein
1 声望0 粉丝