C# 速查表
本文是 C# 编程的快速参考资料,包含常用语法和概念。
数据类型
基本类型
| 类型 | 说明 | 示例 |
|---|---|---|
| int | 32位整数 | int x = 10; |
| long | 64位整数 | long l = 100L; |
| float | 32位浮点 | float f = 3.14f; |
| double | 64位浮点 | double d = 3.14; |
| decimal | 高精度 | decimal m = 3.14m; |
| bool | 布尔 | bool b = true; |
| char | 字符 | char c = 'A'; |
| string | 字符串 | string s = "Hello"; |
集合类型
| 类型 | 说明 |
|---|---|
List\<T> | 动态数组 |
Dictionary<K,V> | 键值对 |
HashSet\<T> | 不重复集合 |
Queue\<T> | 队列 |
Stack\<T> | 栈 |
变量声明
// 基本类型
int age = 25;
string name = "张三";
bool isActive = true;
// 数组
int[] numbers = { 1, 2, 3 };
int[] array = new int[10];
// 集合
var list = new List<int> { 1, 2, 3 };
var dict = new Dictionary<string, int>();
运算符
算术
+ - * / % ++ -- += -= *= /= %=
比较
== != > < >= <=
逻辑
&& || !
位运算
& | ^ ~ << >>
空处理
?? // 空合并
??= // 空合并赋值(C# 8+)
?. // 空条件
控制流
条件
if (condition)
{
// 代码
}
else if (condition2)
{
// 代码
}
else
{
// 代码
}
// 三元
var result = condition ? value1 : value2;
// switch 表达式(C# 8+)
var result = value switch
{
1 => "one",
2 => "two",
_ => "other"
};
循环
for (int i = 0; i < 10; i++)
{
// 代码
}
foreach (var item in collection)
{
// 代码
}
while (condition)
{
// 代码
}
do
{
// 代码
} while (condition);
面向对象
类定义
class Person
{
// 属性
public string Name { get; set; }
// 字段
private int _age;
// 构造函数
public Person(string name)
{
Name = name;
}
// 方法
public void SayHello() => Console.WriteLine($"Hello, {Name}");
}
继承
class Student : Person
{
public Student(string name) : base(name) { }
}
接口
interface IDisposable
{
void Dispose();
}
class MyClass : IDisposable
{
public void Dispose() { }
}
LINQ 查询
方法语法
var result = collection
.Where(x => condition)
.Select(x => transformation)
.OrderBy(x => key)
.GroupBy(x => key)
.ToList();
查询语法
var result = from x in collection
where condition
orderby key
select x.property;
异步编程
async Task<string> GetDataAsync()
{
await Task.Delay(1000);
return "data";
}
// 调用
string data = await GetDataAsync();
多线程
线程创建
Thread t = new Thread(() => { /* 工作代码 */ });
t.IsBackground = true; // 设置为后台线程
t.Start();
t.Join(); // 等待完成
线程池
ThreadPool.QueueUserWorkItem(state => { /* 任务 */ });
Task.Run(() => { /* 任务 */ }); // 推荐
同步机制
// lock 关键字
private readonly object _lock = new object();
lock (_lock) { /* 临界区 */ }
// Monitor
Monitor.Enter(_lock);
try { /* 临界区 */ }
finally { Monitor.Exit(_lock); }
// Mutex(跨进程)
using var mutex = new Mutex(false, "Name");
mutex.WaitOne();
// 临界区
mutex.ReleaseMutex();
// Semaphore(限制并发数)
var sem = new SemaphoreSlim(3, 3);
await sem.WaitAsync();
try { /* 临界区 */ }
finally { sem.Release(); }
// ReaderWriterLockSlim
var rwLock = new ReaderWriterLockSlim();
rwLock.EnterReadLock(); // 读锁
rwLock.EnterWriteLock(); // 写锁
线程安全集合
var queue = new ConcurrentQueue<int>();
queue.Enqueue(item);
queue.TryDequeue(out item);
var dict = new ConcurrentDictionary<string, int>();
dict.AddOrUpdate("key", 1, (k, v) => v + 1);
var collection = new BlockingCollection<int>(100);
collection.Add(item); // 满时阻塞
collection.Take(); // 空时阻塞
collection.CompleteAdding(); // 标记完成
事件同步
var auto = new AutoResetEvent(false); // 自动重置
var manual = new ManualResetEvent(false); // 手动重置
auto.Set(); // 发送信号
auto.WaitOne(); // 等待信号
var countdown = new CountdownEvent(5); // 倒计时
countdown.Signal(); // 计数减一
countdown.Wait(); // 等待归零
var barrier = new Barrier(3); // 屏障
barrier.SignalAndWait(); // 等待所有线程
取消操作
using var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(10));
Task.Run(() => {
for (int i = 0; i < 100; i++) {
cts.Token.ThrowIfCancellationRequested();
// 工作代码
}
}, cts.Token);
原子操作
int counter = 0;
Interlocked.Increment(ref counter); // 原子 ++
Interlocked.Decrement(ref counter); // 原子 --
Interlocked.Add(ref counter, 10); // 原子 +=
Interlocked.Exchange(ref counter, 0); // 原子交换
Interlocked.CompareExchange(ref counter, 1, 0); // 条件交换
常用类库
String
string s = "Hello";
s.Length; // 长度
s.ToUpper(); // 转大写
s.ToLower(); // 转小写
s.Contains("el"); // 是否包含
s.Substring(0, 5); // 子串
s.Split(','); // 分割
s.Trim(); // 去除空格
string.Join(",", arr); // 拼接
File
File.Exists(path); // 检查存在
File.ReadAllText(path); // 读文本
File.WriteAllText(path, str); // 写文本
File.Copy(src, dst); // 复制
File.Move(src, dst); // 移动
File.Delete(path); // 删除
DateTime
DateTime now = DateTime.Now;
DateTime utc = DateTime.UtcNow;
date.AddDays(1); // 加天
date.ToString("yyyy-MM-dd"); // 格式化
DateTime.Parse(str); // 解析
常用快捷键(Visual Studio)
| 快捷键 | 功能 |
|---|---|
| Ctrl + F5 | 运行 |
| Ctrl + K, Ctrl + C | 注释 |
| Ctrl + K, Ctrl + U | 取消注释 |
| Ctrl + K, Ctrl + F | 格式化 |
| Ctrl + . | 快速操作 |
| F12 | 转到定义 |
命名约定
| 类型 | 命名方式 | 示例 |
|---|---|---|
| 类/接口 | 帕斯卡 | class StudentService |
| 方法 | 帕斯卡 | void GetUserById() |
| 属性 | 帕斯卡 | public string Name { get; } |
| 字段 | 下划线+驼峰 | private int _count |
| 参数 | 驼峰 | void SetName(string userName) |
| 常量 | 帕斯卡 | const int MaxRetryCount |
特性(Attributes)
内置特性
[Obsolete("已弃用")] // 标记过时
[Obsolete("已移除", true)] // 编译错误
[Serializable] // 可序列化
[NonSerialized] // 不序列化
[Conditional("DEBUG")] // 条件编译
验证特性
[Required] // 必填
[StringLength(100)] // 长度限制
[Range(0, 100)] // 范围限制
[EmailAddress] // 邮箱格式
[RegularExpression(@"\d+")] // 正则验证
[Compare("Password")] // 比较验证
ASP.NET Core 特性
[ApiController] // API 控制器
[Route("api/[controller]")] // 路由
[HttpGet], [HttpPost] // HTTP 方法
[FromBody], [FromQuery] // 参数绑定
[FromRoute], [FromHeader] // 参数来源
[Authorize], [AllowAnonymous] // 授权
[Produces("application/json")] // 响应类型
Entity Framework 特性
[Table("Users")] // 表名
[Column("user_name")] // 列名
[Key] // 主键
[ForeignKey("Department")] // 外键
[Required] // 非空
[MaxLength(100)] // 最大长度
[NotMapped] // 不映射
[Index(nameof(Email))] // 索引
自定义特性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAttribute : Attribute
{
public string Description { get; }
public MyAttribute(string description) => Description = description;
}
// 读取特性
var attr = typeof(MyClass).GetCustomAttribute<MyAttribute>();