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();
常用类库
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 |