基本语法

翻译整理自 C# 语句、运算符和表达式。

1. 变量声明

int x = 1;
var s = "hello";          // 推断
const double PI = 3.14;

2. 字符串

string s1 = "Hello";
string s2 = $"Hello, {name}!";        // 字符串插值
string s3 = @"C:\new\file";           // 原始字符串
string s4 = """
multi
line
""";                                  // 三引号(C# 11+)
string s5 = s1 + s2;

// 常用方法
s.Length;
s.Substring(0, 3);
s.Contains("ll");
s.Replace("l", "L");
s.Split(',');
s.ToUpper();
string.Join(",", list);

3. 数组

int[] a = new int[3];
int[] b = { 1, 2, 3 };
int[,] m = new int[2, 3];
int[][] jagged = new int[2][];

a.Length;
Array.Sort(b);
Array.ForEach(b, Console.WriteLine);

现代 C# 优先用泛型集合 List<T>、Dictionary<K,V>。

4. 控制流

if (x > 0) { ... }
else if (x == 0) { ... }
else { ... }

switch (op)
{
    case "+": r = a + b; break;
    case "-": r = a - b; break;
    default: throw new InvalidOperationException();
}

// 模式匹配 switch(C# 7+)
var result = shape switch
{
    Circle c => 3.14 * c.R * c.R,
    Square s => s.Side * s.Side,
    _ => 0
};

while (n > 0) n--;
do { n--; } while (n > 0);

for (int i = 0; i < 10; i++) { ... }
foreach (var x in list) { ... }

break; continue; goto label;
return x;

5. 运算符

a + b; a - b; a * b; a / b; a % b;
a++; a--; ++a; --a;
a == b; a != b; a < b; a > b; a <= b; a >= b;
a && b; a || b; !a;
a & b; a | b; a ^ b; ~a; a << 2; a >> 2;
a ? b : c;                            // 三目
x ?? defaultValue;                    // null 合并
x ??= defaultValue;                  // null 合并赋值
a is Type t;                          // 类型检查
a as Type;                            // 转换

6. 异常与 try

try
{
    var v = list[0];
}
catch (IndexOutOfRangeException e)
{
    Console.WriteLine(e.Message);
}
finally
{
    // 必执行
}

7. 命名参数与默认参数

void Print(string msg, int level = 0) { ... }
Print("hello");
Print("hi", 1);
Print(level: 1, msg: "hi");

void M(string a, string b) { ... }
M(b: "y", a: "x");               // 命名参数

8. ref / out / in

void Swap(ref int a, ref int b) { ... }
int x = 1, y = 2;
Swap(ref x, ref y);

bool TryParse(string s, out int n) { n = 0; return false; }
if (TryParse("42", out int v)) { ... }

void Print(in Vec v) { ... }     // in 只读引用

9. 方法局部函数

int Outer(int x)
{
    int Inner(int y) => y * 2;
    return Inner(x);
}

10. 表达式主体

public int X { get; set; }
public string Name => "default";
public void Print() => Console.WriteLine(Name);

小结

C# 语法简洁现代,掌握基本语法后即可开始面向对象编程。