C# 基本语法
语句、注释、大小写敏感、以及几个容易踩的语法细节。
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 3C# 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.
几个细节
| Detail | Note |
|---|---|
| 字符串插值 | $"{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.基本规则
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 3C# 是大小写敏感的语言,Console 和 console 是两个不同的名字。命名惯例是:类型和方法用 PascalCase,局部变量和参数用 camelCase。
注释
C#
// 单行注释
/*
多行注释
*/
/// <summary>
/// XML 文档注释,IDE 会显示在调用处
/// </summary>
/// <param name="x">输入值</param>
/// <returns>两倍</returns>
static int Double(int x) => x * 2;
Console.WriteLine(Double(21));Output
42/// 是 XML 文档注释,编译时可以生成 XML 文件供 IntelliSense 使用。公开 API 都应该写 ///——鼠标悬停就能看到说明。
几个细节
| 细节 | 说明 |
|---|---|
| 字符串插值 | $"{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) 输出的是空行——因为 s 是 null,整个表达式是 int? 类型的 null。这就是空条件运算符的作用:整条链短路。