跳到主要内容

C# 速查表

本文是 C# 编程的快速参考资料,包含常用语法和概念。

数据类型

基本类型

类型说明示例
int32位整数int x = 10;
long64位整数long l = 100L;
float32位浮点float f = 3.14f;
double64位浮点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

参考资料