以下是C#編碼標準,命名規範,還有一些最佳實踐。
在你的項目裏使用這些規範和(或者)調整這些適應你的需求。
類型名稱和方法名稱使用PascalCasing書寫
public class ClientActivity
{
public void ClearStatistics()
{
//...
}
public void CalculateStatistics()
{
//...
}
}
方法參數和局部變量使用camelCasing書寫
public class UserLog
{
public void Add(LogEvent logEvent)
{
int itemCount = logEvent.Items.Count;
// ...
}
}
禁止使用匈牙利標記法或者在標識符前面增加類型標識
// 正確
int counter;
string name;
// 避免
int iCounter;
string strName;
禁止使用大寫標識常量或者只讀型變量
// 正確
public static const string ShippingType = "DropShip";
// 避免
public static const string SHIPPINGTYPE = "DropShip";
避免使用縮寫。例外情況:常用名稱的縮寫,如 Id, Xml, Ftp, Uri
//正確
UserGroup userGroup;
Assignment employeeAssignment;
// 避免
UserGroup usrGrp;
Assignment empAssignment;
// 例外
CustomerId customerId;
XmlDocument xmlDocument;
FtpHelper ftpHelper;
UriPart uriPart;
3個或者3個以上的字母縮寫使用PascalCasing(2個字母使用大寫)
HtmlHelper htmlHelper;
FtpTransfer ftpTransfer;
UIControl uiControl;
標識符不要使用下劃線,例外:私有靜態變量可以使用下劃線
// 正確
public DateTime clientAppointment;
public TimeSpan timeLeft;
// 避免
public DateTime client_Appointment;
public TimeSpan time_Left;
// 例外
private DateTime _registrationDate;
使用預定義的類型名稱替代系統類型名稱,例如Int16, Single, UInt64等
// 正確
string firstName;
int lastIndex;
bool isSaved;
// 避免
String firstName;
Int32 lastIndex;
Boolean isSaved;
局部變量聲明使用隱式類型var。例外:主要類型((int, string, double等)使用預定義的類型。
var stream = File.Create(path);
var customers = new Dictionary();
// 例外
int index = 100;
string timeSheet;
bool isCompleted;
類使用名詞或者名詞短語命名。
public class Employee
{
}
public class BusinessLocation
{
}
public class DocumentCollection
{
}
接口前綴使用字母I,接口名稱使用名詞(名詞短語)或者連接詞。
public interface IShape
{
}
public interface IShapeCollection
{
}
public interface IGroupable
{
}
源文件命名參照他們的主類,例外:部分類的文件名反映他們的來源或目的,例如: designer, generated等。
// Located in Task.cs
public partial class Task
{
//...
}
// Located in Task.generated.cs
public partial class Task
{
//...
}
組織命名空間,命名空間要有清晰明確的結構
// Examples
namespace Company.Product.Module.SubModule
namespace Product.Module.Component
namespace Product.Layer.Module.Group
大括號要豎直對齊
// 正確
class Program
{
static void Main(string[] args)
{
}
}
類的頂部聲明成員變量,靜態類型的變量在最前面
// 正確
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()
{
// ...
}
}
枚舉類型使用單數名稱。例外:位字段枚舉。
// 正確
public enum Color
{
Red,
Green,
Blue,
Yellow,
Magenta,
Cyan
}
// 例外
[Flags]
public enum Dockings
{
None = 0,
Top = 1,
Right = 2,
Bottom = 4,
Left = 8
}
不要顯示指定枚舉的數據類型或者枚舉的值(位字段枚舉除外)
// 避免
public enum Direction : long
{
North = 1,
East = 2,
South = 3,
West = 4
}
// 正確
public enum Direction
{
North,
East,
South,
West
}
不要在枚舉名詞加後綴Enum
//避免
public enum CoinEnum
{
Penny,
Nickel,
Dime,
Quarter,
Dollar
}
// 正確
public enum Coin
{
Penny,
Nickel,
Dime,
Quarter,
Dollar
}
原文地址:
http://www.dofactory.com/reference/csharp-coding-standards