C#命名规则和编码规范

xiaoxiao2021-02-28  58

最近, 要学习一下ASP.NET, 所以需要快速上手, 本人之前学过C++, Java, 对于C#的语法掌握较快, 在网上看到了几篇不错的文章, 所以就转载过来, 毕竟自己是一个坚定的Java的学习者! 用Pascal规则来命名属性、方法、事件和类名public class HelloWorld { public void SayHello(string name) { } }

  Pascal规则是指名称中单词的首字母大写 ,如EmployeeSalary、 ConfimationDialog、PlainTextEncoding。

用Camel规则来命名成员变量、局部变量和方法的参数

public class Product { private string productId; private string productName; public void AddProduct(string productId,string productName) { } }

Camel规则类似于Pascal规则 ,但名称中第一个单词的首字母不大写 ,如employeeSalary、 confimationDialog、plainTextEncoding。

不要使用匈牙利命名法。不要给成员变量加任何前缀(如m、s_等等)。如果想要区分局部变量和成员变量,可以使用this关键字。

不要将常量或者只读变量的变量名全部大写,而使用Pascal规则来命名。

// Correct public static const string ShippingType = "DropShip"; // Avoid public static const string SHIPPINGTYPE = "DropShip"; 接口的名称一般以大写I作前缀。 public interface IConvertible { byte ToByte(); } 自定义的属性以Attribute结尾。 public class TableAttribute:Attribute { }

自定义的异常以Exception结尾。

public class NullEmptyException:Exception { } 类的命名。用名词或名词短语来命名类名。 public class Employee { } public class BusinessLocation { } public class DocumentCollection { } 方法的命名。一般将其命名为动宾短语。 public class File { public void CreateFile(string filePath) { } public void GetPath(string path) { } } 局部变量的名称要有意义。不要直接用i, j, k, l, m, n, x, y, z等做变量名,但for循环除外。所有的成员变量声明在类的顶端,用一个换行把它和方法分开。同时可以使用成对的#region...#endregion标记,方便折叠。布尔型变量或者方法一般可以用is、can或者has做前缀。如,isFinished, canWork等。一般C#的编码风格要求花括号{另起一行,不要直接跟在类名和方法后面。 public Sample() { // TODO: 在此处添加构造函数逻辑 } 可以用缩写作为UI元素的前缀。常见UI组件的一般缩写形式: Label --> lbl、Text --> txt、Button --> btn Image --> img、 Widget --> Wgt、 List --> lst、CheckBox --> chk Hyperlink --> lnk、Panel --> pnl、Table --> tab ImageButton --> imb

判断条件是一个布尔变量时不要使用==进行条件判断。

// 不友好的写法 private bool isFinished = true; if(isFinished == true) { // ... } // 正确的写法 private bool isFinished = true; if(isFinished) { // ... } 变量名是一个单词的尽量不要缩写,多单词组成的变量名可适当缩写。

在类的顶部声明所有的成员变量,静态变量声明在最前面。

// Correct public class Account { public static string BankName; public static decimal Reserves; public string Number {get; set;} public DateTime DateOpened {get; set;} public DateTime DateClosed {get; set;} public decimal Balance {get; set;} // Constructor public Account() { // ... } } 如果一个方法超过25行,就需要考虑是否可以重构和拆分成多个方法。方法命名要见名知意,好的方法名可以省略多余的注释。方法功能尽量单一。

参考文章: http://www.dofactory.com/reference/csharp-coding-standards https://blogs.msdn.microsoft.com/brada/2005/01/26/internal-coding-guidelines/

原文地址:

http://www.jianshu.com/users/fd3eec0ab0f2/latest_articles

下面也是关于C#的一篇好文章,  如果你想在一小时内入门 C#, 可以好好看看, 这篇文章使用例程,简单却完整的探索 C# 语言的构造和特点。特别适合有 C++ 基础或Java基础, 却没有太多精力学习 C# 的程序猿。

个人博客:(一个正在认真学习Java的大二学生)

博客地址

转载请注明原文地址: https://www.6miu.com/read-76070.html

最新回复(0)