C#代码规范要求
1. 注释规范
1.1 类型注释
/// <summary>
/// 老师类
/// </summary>
public class Teacher {}
1.2 方法和属性注释
/// <summary>
/// 根据id查找人的名字
/// </summary>
/// <param name="id">人的id</param>
/// <returns>人的名字</returns>
public string GetPersonName(int id)
{
return "";
}
1.3 单行注释
// 我是注释
1.3 多行注释
/*
多行注释
多行注释
*/
2. 命名规范
2.1 基本命名规范
- 在命名时需要使用有意义的名称
- 优先使用英文,如果英文没有合适的单词,可以使用拼音,如城市名称等
- 禁止使用中文命名
- 命名不能使用缩写,如必须写成 person,不能写成 per
2.2 使用 Pascal 风格(单词首字母大写)命名
- 命名空间
namespace MyApp{}
- 类型
public class Person {}
- 枚举类型、枚举值
public enum Colors
{
Red = 1,
Green = 2,
Yellow = 3
}
- 事件
public event WorkEventHandler OnWork;
- 属性
public string Name { get; set; }
- 方法名
public void Method(){}
- 常量
const int Value = 10;
2.3 使用 Camel 风格(首字母小写,其后每个单词的首字母大写)命名
- 变量
int name;
int personId;
- 方法参数
public void Method(int num){}
- 字段(private 和 protected 字段,需要加“_”前缀)
public class Person
{
private string _name;
}
2.4 其他命名规则
- 接口以 I (大写的 i )为前缀命名
public interface ISpeak {}
- 委托以 EventHandler 作为后缀命名
public delegate void WorkEventHandler ();
- 事件以其对应的委托类型,去掉 EventHandler 后缀,加上 On 前缀
public enent WorkEventHandler OnWork;
- 抽象类以 Abstract 为前缀或者以 Base 为后缀命名
public abstract class AbstractPerson {}
- 异常类型以 Exception 为后缀
public class LoginException {}
3. 布局规范
3.1 使用 Tab 缩进,缩进大小为 4
Visual Studio 2017 中设置方法:菜单工具-选项-文本编辑器-C#-制表符,把制表符大小和缩进大小设置成4,选中“保留制表符”,点确定。
3.2 左右花括号必须独占一行,括号内容为空时可在一行
Visual Studio 2017 中设置方法:菜单工具-选项-文本编辑器-C#-代码样式-格式设置-新行
public void Method(int id)
{
int i = 1;
int j = 2;
}
public void Method(int id) {}
4. 编码规范
4.1. 不能出现公有字段
如果需要公有字段,使用属性包装。
4.2 类型名称和源文件名称必须一致
当类型名称是 Person 时,其源文件名称必须是 Person.cs。
4.3 类型成员的排列顺序
类型成员的排列顺序自上而下:
- 字段:private、protected
- 属性:private、protected、public
- 事件:private、protected、public
- 构造函数:参数越多,排的越靠前
- 方法:参数越多,排的越靠前
public class Person
{
private int _field1;
protected int _field2;
private int _property1 { set; get; }
protected int _property2 { set; get; }
public int Property3 { set; get; }
public Person(int param1, int param2) {}
public Person(int param1) {}
public Person() {}
public string GetPersonName(int param1, int param2) {}
public string GetPersonName(int param1) {}
public string GetPersonName() {}
}