C# 7.0 新特性

C# 7.0 也快要发布了,查看了下new features,感觉C#也越来越有点儿动态语言的感觉了,各种语法糖,用起来爽歪歪哦。


Tuple(函数多返回值)

多返回值是C#7.0的一大亮点啊,除了用out parameter现在可以直接返回元组类型,而且是值类型的,并非引用,有点儿Python的感觉了。

(string, string, string) LookupName(long id) // tuple return type
{ 
    ... // retrieve first, middle and last from data storage 
    return (first, middle, last); // tuple literal
}

可以用Item1,Item2 ... 来获取元组的元素,像这样:

var names = LookupName(id);
WriteLine($"found {names.Item1} {names.Item3}.");

还可以给元组中的元素起一个别名:

(string first, string middle, string last) LookupName(long id) // tuple elements have names

var names = LookupName(id);
WriteLine($"found {names.first} {names.last}.");

还可以直接在返回出定义新变量:

(string first, string middle, string last) = LookupName(id1); // deconstructing declaration
WriteLine($"found {first} {last}.");

是不是找到了Python的感觉呢!

Pattern matching(模式匹配)

可以更方便的判断一个变量的类型来进行下一步操作。也可以用在case中,非常灵活。

public void PrintStars(object o)
{
    if (o is null) return; // constant pattern "null" 
    if (!(o is int i)) return; // type pattern "int i" 
    WriteLine(new string('*', i));
}

用在switch case中就更方便了:

switch(shape)
{
    case Circle c: 
        WriteLine($"circle with radius {c.Radius}");
        break; 
    case Rectangle s when (s.Length == s.Height): 
        WriteLine($"{s.Length} x {s.Height} square"); 
        break; 
    case Rectangle r: 
         WriteLine($"{r.Length} x {r.Height} rectangle"); 
         break; 
    default: 
         WriteLine(""); 
         break; 
    case null: 
         throw new ArgumentNullException(nameof(shape));
}

其他的特性

还有一些特性也使得代码更加简洁:

  • out variables
p.GetCoordinates(out int x, out int y); 
WriteLine($"({x}, {y})");
  • local functions(局部方法)

  • 数字可以加下划线分开,如var d = 123_456;

你可能感兴趣的:(C# 7.0 新特性)