C#基础语法 #
一、程序基本结构 #
1.1 现代C#程序(顶级语句) #
csharp
using System;
Console.WriteLine("Hello, World!");
1.2 传统程序结构 #
csharp
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
1.3 文件范围命名空间(C# 10+) #
csharp
namespace MyApp;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
二、注释 #
2.1 单行注释 #
以//开头,到行尾结束:
csharp
int age = 25;
string name = "张三";
2.2 多行注释 #
以/*开头,以*/结尾:
csharp
int a = 10;
int b = 20;
int c = a + b;
2.3 文档注释 #
以///开头,用于生成API文档:
csharp
/// <summary>
/// 表示一个人的基本信息
/// </summary>
public class Person
{
/// <summary>
/// 获取或设置姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 计算两个数的和
/// </summary>
/// <param name="a">第一个加数</param>
/// <param name="b">第二个加数</param>
/// <returns>两数之和</returns>
public static int Add(int a, int b)
{
return a + b;
}
}
2.4 文档注释标签 #
| 标签 | 用途 |
|---|---|
<summary> |
描述类型或方法 |
<param> |
描述参数 |
<returns> |
描述返回值 |
<exception> |
描述可能抛出的异常 |
<example> |
提供示例代码 |
<see> |
引用其他成员 |
<remarks> |
添加备注说明 |
csharp
/// <summary>
/// 用户服务类
/// </summary>
/// <remarks>
/// 此类提供用户相关的CRUD操作
/// </remarks>
public class UserService
{
/// <summary>
/// 根据ID获取用户
/// </summary>
/// <param name="id">用户ID</param>
/// <returns>用户对象</returns>
/// <exception cref="ArgumentNullException">ID为空时抛出</exception>
/// <exception cref="InvalidOperationException">用户不存在时抛出</exception>
/// <example>
/// <code>
/// var user = userService.GetById(1);
/// </code>
/// </example>
public User GetById(int id)
{
return new User();
}
}
三、标识符 #
3.1 什么是标识符 #
标识符是用来命名变量、方法、类、命名空间等程序元素的名称。
3.2 命名规则 #
必须遵守的规则:
- 只能包含字母、数字、下划线
- 必须以字母或下划线开头
- 不能使用C#关键字(除非加@前缀)
- 区分大小写
csharp
int age = 25;
string _name = "张三";
string userName = "李四";
int @class = 10;
错误示例:
csharp
int 2ndNumber = 10;
string my-name = "张三";
int class = 10;
3.3 命名约定 #
PascalCase(帕斯卡命名法)
每个单词首字母大写:
csharp
public class UserManager { }
public void CalculateTotal() { }
public string FirstName { get; set; }
public const int MaxRetryCount = 3;
camelCase(驼峰命名法)
第一个单词首字母小写,其余首字母大写:
csharp
int totalCount = 0;
string userName = "张三";
void ProcessData(int itemIndex) { }
下划线前缀(私有字段)
csharp
public class MyClass
{
private int _count;
private string _name;
}
3.4 不同类型的命名规范 #
| 类型 | 命名风格 | 示例 |
|---|---|---|
| 命名空间 | PascalCase | MyCompany.MyProject |
| 类 | PascalCase | UserManager |
| 接口 | PascalCase + I前缀 | IUserService |
| 方法 | PascalCase | GetUserById |
| 属性 | PascalCase | UserName |
| 公有字段 | PascalCase | MaxSize |
| 私有字段 | _camelCase | _count |
| 局部变量 | camelCase | totalCount |
| 参数 | camelCase | userId |
| 常量 | PascalCase或UPPER_CASE | MaxRetryCount |
四、关键字 #
4.1 保留关键字 #
C#保留关键字不能用作标识符:
csharp
abstract as base bool break byte case
catch char checked class const continue
decimal default delegate do double else
enum event explicit extern false finally
fixed float for foreach goto if
implicit in int interface internal is
lock long namespace new null object
operator out override params private protected
public readonly ref return sbyte sealed
short sizeof stackalloc static string struct
switch this throw true try typeof
uint ulong unchecked unsafe ushort using
virtual void volatile while
4.2 上下文关键字 #
上下文关键字在特定上下文中才有特殊含义:
csharp
add alias ascending async await by
descending dynamic equals from get global
group into join let nameof on
orderby partial remove select set value
var when where yield
4.3 使用@前缀 #
如果必须使用关键字作为标识符,可以加@前缀:
csharp
int @class = 10;
string @string = "Hello";
void @static() { }
但通常不建议这样做,应选择其他名称。
五、语句与块 #
5.1 语句 #
语句是程序的最小执行单位,以分号结尾:
csharp
int x = 10;
Console.WriteLine(x);
return;
5.2 代码块 #
代码块用大括号包围:
csharp
if (x > 0)
{
Console.WriteLine("正数");
}
5.3 空语句 #
单独的分号表示空语句:
csharp
;
六、空白与格式 #
6.1 空白字符 #
C#忽略多余的空白字符:
csharp
int x=10;
int x = 10;
int x = 10;
6.2 代码格式建议 #
缩进
使用4个空格或1个Tab:
csharp
if (condition)
{
if (nested)
{
DoSomething();
}
}
大括号风格
Allman风格:
csharp
if (condition)
{
DoSomething();
}
K&R风格:
csharp
if (condition) {
DoSomething();
}
空行
在逻辑块之间添加空行:
csharp
public class Calculator
{
private int _result;
public void Clear()
{
_result = 0;
}
public int Add(int value)
{
_result += value;
return _result;
}
}
七、表达式 #
7.1 字面量 #
csharp
int number = 42;
double pi = 3.14;
char letter = 'A';
string text = "Hello";
bool flag = true;
7.2 数字字面量格式 #
csharp
int decimalNum = 42;
int hexNum = 0x2A;
int binaryNum = 0b101010;
double scientific = 1.5e10;
float floatNum = 3.14f;
decimal money = 100.50m;
int readable = 1_000_000;
7.3 字符串字面量 #
常规字符串
csharp
string text = "Hello, World!";
string escaped = "Line1\nLine2\tTabbed";
逐字字符串
csharp
string path = @"C:\Users\Documents";
string json = @"{""name"": ""张三""}";
原始字符串(C# 11+)
csharp
string json = """
{
"name": "张三",
"age": 25
}
""";
八、运算符优先级 #
8.1 优先级表(从高到低) #
| 优先级 | 运算符 |
|---|---|
| 1 | x.y, f(x), a[i], x++, x--, new, typeof |
| 2 | +, -, !, ~, ++x, --x, (T)x |
| 3 | *, /, % |
| 4 | +, - |
| 5 | <<, >> |
| 6 | <, >, <=, >=, is, as |
| 7 | ==, != |
| 8 | & |
| 9 | ^ |
| 10 | | |
| 11 | && |
| 12 | || |
| 13 | ??, ??= |
| 14 | ?: |
| 15 | =, +=, -=, *=, /=, &=, |=, ^=, <<=, >>= |
8.2 使用括号明确优先级 #
csharp
int result1 = 2 + 3 * 4;
int result2 = (2 + 3) * 4;
九、代码规范最佳实践 #
9.1 命名规范 #
csharp
public class UserService
{
private readonly IUserRepository _userRepository;
private const int MaxRetryCount = 3;
public string UserName { get; set; }
public User GetUserById(int userId)
{
var user = _userRepository.Find(userId);
return user;
}
}
9.2 代码组织 #
csharp
public class MyClass
{
private int _privateField;
public int PublicProperty { get; set; }
public MyClass()
{
}
public void PublicMethod()
{
}
private void PrivateMethod()
{
}
}
9.3 EditorConfig配置 #
ini
[*.cs]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
dotnet_sort_system_directives_first = true
csharp_new_line_before_open_brace = all
十、总结 #
C#基础语法要点:
| 要点 | 说明 |
|---|---|
| 注释 | //、/* */、/// |
| 标识符 | 字母、数字、下划线组成 |
| 关键字 | 保留字,不能用作标识符 |
| 命名规范 | PascalCase、camelCase |
| 语句 | 以分号结尾 |
| 代码块 | 用大括号包围 |
下一步,让我们学习C#的数据类型!
最后更新:2026-03-26