好的代碼應該擁有以下幾個特征:
代碼容易編寫,並易於修改和擴展。
代碼干淨,並表述准確。
代碼有價值,並注重質量。
符合微軟規范並易讀
1. 類名和方法名使用 PascalCasing.
public class ClientActivity
{
public void ClearStatistics()
{
//...
}
public void CalculateStatistics()
{
//...
}
}
2. 方法參數和局部變量使用 camelCasing
public class UserLog
{
public void Add(LogEvent logEvent)
{
int itemCount = logEvent.Items.Count;
// ...
}
}
3. 不要使用Hungarian notation或者其他類型標識在標識符
// Correct
int counter;
string name;
// Avoid
int iCounter;
string strName;
4. 不要對常量和只讀變量使用Screaming Caps
// Correct
public static const string ShippingType = "DropShip";
// Avoid
public static const string SHIPPINGTYPE = "DropShip";
5. 避免使用縮寫.例外: abbreviations commonly used as names, such as Id, Xml, Ftp, Uri
// Correct
UserGroup userGroup;
Assignment employeeAssignment;
// Avoid
UserGroup usrGrp;
Assignment empAssignment;
// Exceptions
CustomerId customerId;
XmlDocument xmlDocument;
FtpHelper ftpHelper;
UriPart uriPart;
6. 縮寫3個以上字符 (2 chars are both uppercase)使用PascalCasing
HtmlHelper htmlHelper;
FtpTransfer ftpTransfer;
UIControl uiControl;
7. 不要使用在標識符使用下劃線. 例外: you can prefix private static variables
with an underscore.
// Correct
public DateTime clientAppointment;
public TimeSpan timeLeft;
// Avoid
public DateTime client_Appointment;
public TimeSpan time_Left;
// Exception
private DateTime _registrationDate;
8. 使用預定義類型名而不是系統類型名如 Int16, Single, UInt64, 等
// Correct
string firstName;
int lastIndex;
bool isSaved;
// Avoid
String firstName;
Int32 lastIndex;
Boolean isSaved;
9. 局部變量聲明使用隱式類型 var. 例外Exception: primitive types (int, string,
double, etc) use predefined names.
var stream = File.Create(path);
var customers = new Dictionary();
// Exceptions
int index = 100;
string timeSheet;
bool isCompleted;
10. 使用名稱或名詞短語來命名類.
public class Employee
{
}
public class BusinessLocation
{
}
public class DocumentCollection
{
}
11. 接口前綴帶I. 接口名是名詞(短語)或者形容詞.
public interface IShape
{
}
public interface IShapeCollection
{
}
public interface IGroupable
{
}
12. 根據主類命名來源文件. 例外: file names with partial classes
reflect their source or purpose, e.g. designer, generated, etc.
// Located in Task.cs
public partial class Task
{
//...
}
// Located in Task.generated.cs
public partial class Task
{
//...
}
13. 清晰的定義結構來組織命名空間
// Examples
namespace Company.Product.Module.SubModule
namespace Product.Module.Component
namespace Product.Layer.Module.Group
14. 花括號要豎向排列
// Correct
class Program
{
static void Main(string[] args)
{
}
}
15.在類頭部聲明所有的成員變量, 靜態變量在最頭部.
// 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()
{
// ...
}
}
16. 使用單數命名枚舉. 例外: bit field enums.
// Correct
public enum Color
{
Red,
Green,
Blue,
Yellow,
Magenta,
Cyan
}
// Exception
[Flags]
public enum Dockings
{
None = 0,
Top = 1,
Right = 2,
Bottom = 4,
Left = 8
}
17. 不要顯式指定枚舉的類型或者枚舉的值(except bit fields)
// Don't
public enum Direction : long
{
North = 1,
East = 2,
South = 3,
West = 4
}
// Correct
public enum Direction
{
North,
East,
South,
West
}
18. 不要用Enum做後綴命名枚舉
// Don't
public enum CoinEnum
{
Penny,
Nickel,
Dime,
Quarter,
Dollar
}
// Correct
public enum Coin
{
Penny,
Nickel,
Dime,
Quarter,
Dollar
}
補充
1. 類型名和源文件名詞一致
如類型名Product,源文件命名Product.cs
2.方法的命名。一般將其命名為動賓短語。
public class File
{
public void CreateFile(string filePath)
{
}
public void GetPath(string path)
{
}
}
3、類型成員的排列順序
類型成員的排列順序自上而下依次為:
字段:私有字段、受保護字段
屬性:私有屬性、受保護屬性、公有屬性
事件:私有事件、受保護事件、公有事件
構造函數:參數數量最多的構造函數,參數數量中等的構造函數,參數數量最少的構造函數
方法:重載方法的排列順序與構造函數相同,從參數數量最多往下至參數最少
Public class Product
{
private int field1;
protect int field2;
privite int property1{get;set;}
protect int property2{get;set;}
Public int Property3{get;set;}
private SalesOutEventHander event1;
protect SalesOutEventHander event2;
public SalesOutEventHander Event3;
public Product(int param1, int param2)
{
}
public Product(int param1)
{
}
public Product()
{
}
public Product GetProduct(int id,string area)
{
return null;
}
public Product GetProduct(int id)
{
return null;
}
public Product GetProduct()
{
return null;
}
}
4、委托和事件的命名
委托以EventHandler作為後綴命名,例如 SalesOutEventHandler。
事件以其對應的委托類型,去掉EventHandler後綴,並加上On前綴構成。
public delegate void SalesOutEventHander();
public class Product
{
public SalesOutEventHander OnSalesOut;
}
5、返回bool類型的方法、屬性的命名
如果方法返回的類型是bool類型,則其前綴為Is,例如:IsHidden。
如果某個屬性的類型為bool類型,則其前綴為Can,例如:CanHidden。
6、常見集合後綴類型命名
凡符合下表所列的集合類型,應添加相應的後綴。
Array int[] productArray
List List<Product> productList
Table HashTable productTable
Dictionary Dictionary<string,string> productDictionary
Set DbSet<Product> productSet
7、常見字段、屬性命名
字段、屬性種類比較繁雜,因此僅列出最常用的幾項
Id GuidId Name Title Remark Category Linkman