C# 基本语法

语句、注释、大小写敏感、以及几个容易踩的语法细节。

Beginner
Key PointsC# 严格区分大小写,语句必须用分号结束,代码块用花括号。

基本规则

C#
using System;

class Program
{
    static void Main()
    {
        int a = 1;              // 语句必须以分号结束
        int b = 2;
        Console.WriteLine(a + b);

        if (a < b)
        {                       // 花括号可以另起一行
            Console.WriteLine("a 小于 b");
        }
    }
}
Output
3
a 小于 b

大小写敏感

C#
int value = 1;
int Value = 2;
int VALUE = 3;

Console.WriteLine($"{value} {Value} {VALUE}");

// Console 不能写成 console
// console.WriteLine("x");   // 编译错误
Output
1 2 3

C# is case-sensitive: Console and console are different names. Convention: PascalCase for types and methods, camelCase for locals and parameters.

注释

C#
// 单行注释

/*
   多行注释
*/

/// <summary>
/// XML 文档注释,IDE 会显示在调用处
/// </summary>
/// <param name="x">输入值</param>
/// <returns>两倍</returns>
static int Double(int x) => x * 2;

Console.WriteLine(Double(21));
Output
42

/// is an XML doc comment; the compiler can emit an XML file for IntelliSense. Public APIs should have them so hovering shows documentation.

几个细节

DetailNote
字符串插值$"{x}",C# 6+
逐字字符串@"C:\path",反斜杠不转义
原始字符串"""...""",C# 11+,不用转义
表达式体=> expr 代替 { return expr; }
空合并a ?? b,a 为 null 时取 b
空条件a?.b,a 为 null 时整体为 null
C#
var name = "世界";
Console.WriteLine($"你好,{name}");            // 插值
Console.WriteLine(@"C:\temp\a.txt");           // 逐字
Console.WriteLine("""
    原始字符串里 "引号" 和 \反斜杠 都不用转义
    """);

string? s = null;
Console.WriteLine(s ?? "默认值");
Console.WriteLine(s?.Length);
Output
你好,世界
C:\temp\a.txt
原始字符串里 "引号" 和 \反斜杠 都不用转义
默认值
Console.WriteLine(s?.Length) prints an empty line — s is null, so the expression is null of type int?. That is what ?. does: the whole chain short-circuits.

Friends & Partners