Cheat Sheet速查表
跳转到主要内容

C# 7 速查表

本文根据 Devhints / C# 7 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2018-12-06。

输出变量 (Out Variables)

public void PrintCoordinates(Point p)
{
    p.GetCoordinates(out int x, out int y);
    WriteLine($"({x}, {y})");
}

out 用于在将变量作为参数传递的位置声明该变量。

模式匹配

带模式的 `is` 表达式

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` 语句

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("<unknown shape>");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
}

元组

元组类型

(string, string, string) LookupName(long id) // tuple return type
{
    ... // retrieve first, middle and last from data storage
    return (first, middle, last); // tuple literal
}
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}.");

元组字面量

   return (first: first, middle: middle, last: last); // named tuple elements in a literal

元组解构

(var first, var middle, var last) = LookupName(id1);
WriteLine($"found {first} {last}.");

或

var (first, middle, last) = LookupName(id1); // var outside

或

(first, middle, last) = LookupName(id2); // assign onto existing variables

局部函数

public int Fibonacci(int x)
{
    if (x < 0) throw new ArgumentException("Less negativity please!", nameof(x));
    return Fib(x).current;

    (int current, int previous) Fib(int i)
    {
        if (i == 0) return (1, 0);
        var (p, pp) = Fib(i - 1);
        return (p + pp, p);
    }
}

字面量改进

数字字面量中的数字分隔符

var d = 123_456;
var x = 0xAB_CD_EF;

二进制字面量

var b = 0b1010_1011_1100_1101_1110_1111;

引用返回值与局部变量 (`ref` 返回值和局部变量)

public ref int Find(int number, int[] numbers)
{
    for (int i = 0; i < numbers.Length; i++)
    {
        if (numbers[i] == number)
        {
            return ref numbers[i]; // return the storage location, not the value
        }
    }
    throw new IndexOutOfRangeException($"{nameof(number)} not found");
}

int[] array = { 1, 15, -39, 0, 7, 14, -12 };
ref int place = ref Find(7, array); // aliases 7's place in the array
place = 9; // replaces 7 with 9 in the array
WriteLine(array[4]); // prints 9

更多表达式体成员

C# 7.0 版本将访问器、构造函数和终结器也纳入了支持“表达式体”的成员列表中:

class Person
{
    private static ConcurrentDictionary<int, string> names = new ConcurrentDictionary<int, string>();
    private int id = GetId();

    public Person(string name) => names.TryAdd(id, name); // constructors
    ~Person() => names.TryRemove(id, out *);              // destructors
    public string Name
    {
        get => names[id];                                 // getters
        set => names[id] = value;                         // setters
    }
}

`throw` 表达式

class Person
{
    public string Name { get; }
    public Person(string name) => Name = name ?? throw new ArgumentNullException(name);
    public string GetFirstName()
    {
        var parts = Name.Split(" ");
        return (parts.Length > 0) ? parts[0] : throw new InvalidOperationException("No name!");
    }
    public string GetLastName() => throw new NotImplementedException();
}