IDesign C#編程規範

1 命名規則和風格 naming conventions and style
2 編碼慣例 coding practices
3 項目設置和結構 project settings and structure
4 framework特別指導 framework specific guidelines
4.1 數據訪問 data access
4.2 asp.net和web service asp.net and web services
4.3 序列化 serialization
4.4 多線程 multithreading
4.5 remoting remoting
4.6 安全 security
4.7 服務組件 enterprise services
5 資源 resources


今天只翻譯了命名規則部分,譯文及原文對照如下,其中的tip是附加的,:-)



命名規則和風格
naming conventions and style


1. 類和方法名採用pascal風格
use pascal casing for type and method names
public class someclass
{
public somemethod(){}
}
2. 局部變量和方法參數採用camel風格
use camel casing for local variable names and method arguments
int number;
void mymethod(int somenumber)
{}
3. 接口名採用i作爲前綴
prefix interface name with i
interface imyinterface
{..}
4. 私有成員變量採用m_作爲前綴
prefix private member variables with m_
public class someclass
{
private int m_number;
}
5. 自定義屬性類名採用attribute作爲後綴
suffix custom attribute classes with attribute.
6. 自定義異常類名採用exception作爲後綴
suffix custom exception classes with exception.
7. 採用動詞-對象對命名方法,例如showdialog()
name methods using verb-object pair, such as showdialog()
8. 有返回值的方法應該取名錶示其返回值,例如getobjectstate()
methods with return values should have a name describing the value returned, such as getobjectstate().
9. 採用描述性的變量名。
use descriptive variable names.
a) 避免採用單字母的變量名,如i或t;而是採用index或temp。
avoid single character variable names, such as i or t. use index or temp instead.
b) 對public和protected成員避免採用用匈牙利命名法。
avoid using hungarian notation for public or protected members.
c) 不要採用縮寫(例如將number縮寫爲num)。
do not abbreviate words (such as num instead of number).
10. 總是使用c#預定義的類型,而不是使用system命名空間中的別名。例如:採用object不用object,採用string不用string,採用int不用int32。
always use c# predefined types rather than the aliases in the system namespace.
for example:
object not object
string not string
int not int32
11. 對於泛型,類型採用大寫字母。當處理.net類型type時保留後綴type。
with generics, use capital letters for types. reserve suffixing type when dealing with the .net type type.
// 正確:
//correct:
public class linkedlist
// 避免使用:
//avoid:
public class linkedlist
12. 採用有意義的命名空間名,例如產品名稱或公司名稱。
use meaningful namespaces such as the product name or the company name.
13. 避免使用類的全稱,而是採用using語句。
avoid fully qualified type names. use the using statement instead.
14. 避免在命名空間內使用using語句。
avoid putting a using statement inside a namespace.
15. 將所有framework命名空間名放在一起,後面放自定義或第三方的命名空間名。
group all framework namespaces together and put custom or third party namespaces underneath.
using system;
using system.collections;
using system.componentmodel;
using system.data;
using mycompany;
using mycontrols;
16. 採用委託推斷,不要顯式實例化委託。
use delegate inference instead of explicit delegate instantiation
delegate void somedelegate();
public void somemethod()
{}
somedelegate somedelegate = somemethod;
17. 嚴格遵守縮進格式。
maintain strict indentation.
a) 縮進採用3個空格。
use 3 spaces for indentation.
b) 不用採用tab或非標準的縮進,如1、2或4個空格。
do not use tabs or non-standard indentation like 1, 2 or 4 spaces.
18. 註釋縮進和其註釋的代碼在同一層次。
indent comment at the same level of indentation as the code you are documenting.
19. 所有註釋要經過拼寫檢查。拼寫錯誤的註釋表明開發的草率。
all comments should pass spell checking. misspelled comments indicate sloppy development.
20. 所有成員變量應該定義在前面,和屬性或方法間空開一行。
all member variables should be declared at the top, with one line separating them from the properties or methods.
public class myclass
{
int m_number;
string m_name;


public void somemethod1()
{}
public void somemethod2()
{}
}
21. 局部變量的定義儘可能靠近它的初次使用。
declare a local variable as close as possible to its first use.
22. 文件名應該體現其包含的類。
a file name should reflect the class it contains.
23. 當使用partial類型且每部分分配一個文件時,以類型名加p和序數命名每個文件。
when using partial types and allocating a part per file, name each file after the type suffixed with a p and an ordinal number:
//in myclassp1.cs
public partial class myclass
{}
//in myclassp2.cs
public partial class myclass
{}
24. 左大括號總是放在新行中。
always place an open curly brace ({) in a new line.
25. 匿名方法模仿普通方法的佈局,和匿名委託定義放在一行。
with anonymous methods mimic the code layout of a regular method, aligned with the anonymous delegate declaration.
a) 遵守將左大括號放在新行的規則。
comply with placing an open curly brace in a new line
delegate void somedelegate(string somestring);
//正確
//correct:
public void invokemethod()
{
somedelegate somedelegate = delegate(string name)
{
messagebox.show(name);
};
somedelegate("juval");
}
//避免採用:
//avoid
public void invokemethod()
{
somedelegate somedelegate = delegate(string name){messagebox.show(name);};
somedelegate("juval");
}
26. 沒有參數的匿名方法使用空括號。
use empty parenthesis on parameter-less anonymous methods
a) 僅當匿名方法可能被用於任何委託時省略括號。
omit the parenthesis only if the anonymous method could have been used on any delegate.
delegate void somedelegate();
//correct
somedelegate somedelegate1 = delegate()
{
messagebox.show("hello");
};
//avoid
somedelegate somedelegate1 = delegate
{
messagebox.show("hello");
};
2 編碼慣例
coding practices



1. 避免在一個文件中放多個類。
avoid putting multiple classes in a single file.
2. 一個文件應該只對一個命名空間提供類型。避免在同一文件中有多個命名空間。
a single file should only contribute types to a single namespace. avoid having multiple namespaces in the same file.
3. 避免文件長度超過500行(除了機器自動產生的代碼)。
avoid files with more than 500 lines (excluding machine-generated code).
4. 避免方法定義超過25行。
avoid methods with more than 25 lines.
5. 避免超過5個參數的方法。使用結構傳遞多個參數。
avoid methods with more than 5 arguments. use structures for passing multiple arguments.
6. 每行應該不超過80個字符。
lines should not exceed 80 characters.
7. 不要手工編輯任何機器生成的代碼。
do not manually edit any machine generated code.
a) 如果修改機器生成的代碼,修改代碼格式和風格以符合本編碼標準。
if modifying machine generated code, modify the format and style to match this coding standard.
b) 儘可能採用partial類以分解出需要維護的部分。
use partial classes whenever possible to factor out the maintained portions.
8. 避免對顯而易見的內容作註釋。
avoid comments that explain the obvious.
a) 代碼應該是自解釋的。 由可讀性強的變量和方法組成的好的代碼應該不需要註釋。
code should be self explanatory. good code with readable variable and method names should not require comments.
9. 僅對操作的前提、內在算法等寫文檔。
document only operational assumptions, algorithm insights and so on.
10. 避免方法級的文檔。
avoid method-level documentation.
a) 對api文檔採用大量的外部文檔。
use extensive external documentation for api documentation.
b) 方法級註釋僅作爲對其他開發人員的提示。
use method-level comments only as tool tips for other developers.
11. 決不要硬編碼數值, 而總是聲明一個常量。
never hard-code a numeric value, always declare a constant instead.
12. 僅對本來就是常量的值使用const修飾符,例如一週的天數。
use the const directive only on natural constants such as the number of days of week.
13. 避免對只讀變量使用const修飾符。在此情況下,採用readonly修飾符。
avoid using const on read-only variables. for that, use the readonly directive.
public class myclass
{
public readonly int number;
public myclass(int somevalue)
{
number = somevalue;
}
public const int daysinweek = 7;
}
14. 對任何假設採用assert。
assert every assumption.
a) 平均地,每5行中就有一行是斷言。
on average, every fifth line is an assertion.
using system.diagnostics;
object getobject()
{
object obj = getobject();
debug.assert(obj != null);
15. 每行代碼應該經過白盒測試。
every line of code should be walked through in a 搘hite box?testing manner.
16. 僅捕獲已經顯式處理了的異常。
only catch exceptions for which you have explicit handling.
17. 在拋出異常的catch語句中,總是拋出最初異常以保持最初錯誤的堆棧位置。
in a catch statement that throws an exception, always throw the original exception to maintain stack location of original error.
catch(exception exception)
{
messagebox.show(exception.message);
throw; //same as throw exception;
}
18. 避免將錯誤代碼作爲方法的返回值。
avoid error code as methods return values.
19. 避免定義自定義的異常類。
avoid defining custom exception classes.
20. 定義自定義異常時:
when defining custom exceptions:
a) 從applicationexception繼承
derive the custom exception from applicationexception.
b) 提供自定義的序列化。
provide custom serialization.
21. 避免在一個程序集中有多個main()方法。
avoid multiple main() methods in a single assembly.
22. 僅對最需要的類型標記爲public,其他的標記爲internal。
make only the most necessary types public, mark others as internal.
23. 避免採用friend程序集,因爲這樣增加了程序集間的耦合度。
avoid friend assemblies, as it increases inter-assembly coupling.
24. 避免使用依賴於從特定位置運行的程序集的代碼。
avoid code that relies on an assembly running from a particular location.
25. 儘量減少應用程序集(客戶端exe程序集)的代碼。採用類庫而不要包含業務邏輯層代碼。
minimize code in application assemblies (exe client assemblies). use class libraries instead to contain business logic.
26. 避免對枚舉提供明確的值。
avoid providing explicit values for enums .
//correct
public enum color
{
red,green,blue
}
//avoid
public enum color
{
red = 1,green = 2,blue = 3
}
27. 避免對枚舉指定類型。
avoid specifying a type for an enum.
//avoid
public enum color : long
{
red,green,blue
}
28. if語句總是使用括號,即使它包含一句語句。
always use a curly brace scope in an if statement, even if it conditions a single statement.
29. 避免使用?:條件算符。
avoid using the trinary conditional operator.
30. 避免在布爾條件語句中調用函數。賦值到局部變量並檢查它們的值。
avoid function calls in boolean conditional statements. assign into local variables and check on them:
bool iseverythingok()
{...}
//避免:
//avoid:
if(iseverythingok())
{...}
//採用:
//instead:
bool ok = iseverythingok();
if(ok)
{...}
31. 總是使用從0開始的數組。
always use zero-based arrays.
32. 總是使用一個for循環顯式地初始化一個引用類型的數組。
always explicitly initialize an array of reference types using a for loop.
public class myclass
{}
myclass[] array = new myclass[100];
for(int index = 0; index < array.length; index++)
{
array[index] = new myclass();
}
33. 不用提供public或protected成員變量,而是使用屬性。
do not provide public or protected member variables. use properties instead.
34. 避免使用new繼承修飾符,而是使用override。
avoid using the new inheritance qualifier. use override instead.
35. 對非密封類總是將public和protected方法標記爲virtual。
always mark public and protected methods as virtual in a non sealed class.
36. 除非涉及到互操作,永遠不要用不安全的代碼。
never use unsafe code unless when using interop.
37. 避免顯式類型轉換。使用as算法防護性地轉換類型。
avoid explicit casting. use the as operator to defensively cast to a type.
dog dog = new germanshepherd();
germanshepherd shepherd = dog as germanshepherd;
if(shepherd != null)
{...}
38. 類成員有委託時:
with delegates as class members:
a) 使用前將委託複製到局部變量,以避免併發衝突。
copy a delegate to a local variable before publishing to avoid concurrency race condition.
b) 調用前始終檢查委託是否爲空。
always check a delegate for null before invoking it.
public class mysource
{
public event eventhandler myevent;
public void fireevent()
{
eventhandler temp = myevent;
if(temp != null)
{
temp(this,eventargs.empty);
}
}
}
39. 不要提供public的事件成員變量,而是使用事件訪問器。
do not provide public event member variables. use event accessors instead.
public class mysource
{
mydelegate m_someevent;
public event mydelegate someevent
{
add
{
m_someevent += value;
}
remove
{
m_someevent -= value;
}
}
}
40. 使用programming .net components中定義的eventshelper類安全地發佈事件。
use the eventshelper class defined in programming .net components to publish events defensively.
41. 總是使用接口。
always use interfaces.
a) 參見programming .net components第一和第三章。
see chapters 1 and 3 in programming .net components.
42. 類和接口中方法和屬性的比例至少是2:1。
classes and interfaces should have at least 2:1 ratio of methods to properties.
43. 避免使用一個成員的接口。
avoid interfaces with one member.
44. 努力使每個接口擁有3-5個成員。
strive to have 3-5 members per interface.
45. 每個接口不用超過20個成員。
no more than 20 members per interface.
a) 12可能是實際應用的極限了。
12 is probably a practical limit.
46. 避免將事件作爲接口成員。
avoid events as interface members.
47. 避免使用抽象方法,而是使用接口代替。
avoid abstract methods, use interfaces instead.
48. 在類層次中暴露接口。
expose interfaces on class hierarchies.
a) 參見programming .net components第三章。
see chapter 3 in programming .net components.
49. 優先使用明確的接口實現。
prefer using explicit interface implementation.
a) 參見programming .net components第三章。
see chapter 3 in programming .net components.
50. 永遠不要假設一種類型支持某個接口。防護性地檢查是否支持該接口。
never assume a type supports an interface. defensively query for that interface.
sometype obj1;
imyinterface obj2;

/* some code to initialize obj1, then: */
obj2 = obj1 as imyinterface;
if(obj2 != null)
{
obj2.method1();
}
else
{
//handle error in expected interface
}
51. 將呈現給用戶的字符串永遠不用硬編碼,而是使用資源。
never hardcode strings that will be presented to end users. use resources instead.
52. 發佈時可能修改的字符串永遠不用硬編碼,例如連接字符串。
never hardcode strings that might change based on deployment such as connection strings.
53. 構建一個長字符串時,使用stringbuilder,不要用string。
when building a long string, use stringbuilder, not string.
54. 避免提供帶結構的方法。
avoid providing methods on structures.
a) 參數化的構造函數是鼓勵使用的。
parameterized constructors are encouraged.
b) 可以重載算符。
can overload operators.
55. 當提供靜態成員變量時,總是提供一個靜態構造函數。
always provide a static constructor when providing static member variables.
56. 只要可以用前期綁定就不要用後期綁定。
do not use late-binding invocation when early-binding is possible.
57. 對應用程序進行日誌和跟蹤。
use application logging and tracing.
58. 除非在switch語句中跳轉,永遠不要用goto語句。
never use goto unless in a switch statement fall-through.
59. switch語句中總是使用default用於加斷言。
always have a default case in a switch statement that asserts .
int number = somemethod();
switch(number)
{
case 1:
trace.writeline("case 1:");
break;
case 2:
trace.writeline("case 2:");
break;
default:
debug.assert(false);
break;
}
60. 除非在構造函數中調用另一個構造函數,否則不用使用this。
do not use the this reference unless invoking another constructor from within a constructor.
//example of proper use of this
public class myclass
{
public myclass(string message)
{}
public myclass() : this("hello")
{}
}
61. 除非爲了解決調用基類構造函數時成員名的衝突,否則不要使用base訪問基類的成員。
do not use the base word to access base class members unless you wish to resolve a conflict with a subclasses member of the same name or when invoking a base class constructor.
//example of proper use of 抌ase?
public class dog
{
public dog(string name)
{}
virtual public void bark(int howlong)
{}
}
public class germanshepherd : dog
{
public germanshepherd(string name): base(name)
{}
override public void bark(int howlong)
{
base.bark(howlong);
}
}
62. 根據programming .net components第四章中的模板實現dispose()和finalize()方法。
implement dispose() and finalize() methods based on the template in chapter 4 of programming .net components.
63. 使用泛型的代碼中避免與system.object進行類型轉換,而是使用限制或as算符。
avoid casting to and from system.object in code that uses generics. use constraints or the as operator instead:
class someclass
{}
//避免 avoid:
class myclass
{
void somemethod(t t)
{
object temp = t;
someclass obj = (someclass)temp;
}
}
//正確 correct:
class myclass where t : someclass
{
void somemethod(t t)
{
someclass obj = t;
}
}
64. 泛型接口不要定義限制。接口層的限制通常能用強類型代替。
do not define constraints in generic interfaces. interface level-constraint can often be replaced by strong-typing.
public class customer
{...}
//避免 avoid:
public interface ilist where t : customer
{...}
//正確 correct:
public interface icustomerlist : ilist
{...}
65. 不要在接口中定義與方法相關的限制。
do not define method-specific constraints in interfaces.
66. 在數據結構中總是優先使用c#泛型。
always prefer using c# generics in data structures.
3 項目設置和項目結構
Project Settings and Project Structure



1. 總是以4級警告建立項目(圖略)。
Always build your project with warning level 4
2. 在發佈版中將警告作爲錯誤(注意這不是VS.NET的缺省設置)(圖略)。
Treat warning as errors in Release build (note that this is not the default of VS.NET).
a) 雖然是可選的,本標準也推薦在調試版中將警告作爲錯誤。
Although it is optional, this standard recommend treating warnings as errors in debug builds as well.
3. 永遠不要抑制特定的編譯警告(圖略)。
Never suppress specific compiler warnings.
4. 總是在應用程序的配置文件中顯式地說明支持的運行時版本。參見Programming .NET Components第五章。
Always explicitly state your supported runtime versions in the application configuration file. See Chapter 5 in Programming .NET Components.
<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v2.0.0.0"/>
<supportedRuntime version="v1.1.5000.0"/>
</startup>
</configuration>
5. 避免顯式地自定義版本改向和綁定到CLR程序集。
Avoid explicit custom version redirection and binding to CLR assemblies.
6. 避免顯式的預編譯定義(#define)。使用項目設置定義條件編譯常量。
Avoid explicit preprocessor definitions (#define). Use the project settings for defining conditional compilation constants.
7. 不要在AssemblyInfo.cs中放任何邏輯。
Do not put any logic inside AssemblyInfo.cs.
8. 除了在AssemblyInfo.cs,不要在任何文件中放程序集屬性。
Do not put any assembly attributes in any file besides AssemblyInfo.cs.
9. 在AssemblyInfo.cs中提供所有字段,例如公司名稱、描述、版權等。
Populate all fields in AssemblyInfo.cs such as company name, description, copyright notice.
10. 所有程序集應該使用相對路徑引用。
All assembly references should use relative path.
11. 不允許在程序集中循環引用。
Disallow cyclic references between assemblies.
12. 避免多模塊的程序集。
Avoid multi-module assemblies.
13. 缺省總是以非檢查的方式運行(爲了性能考慮),但是對易於溢出或下溢的操作顯式使用檢查模式(圖略)。
Always run code unchecked by default (for performance sake), but explicitly in checked mode for overflow or underflow prone operations.
int CalcPower(int number,int power)
{
int result = 1;
for(int count = 1;count <= power;count++)
{
checked
{
result *= number;
}
}
return result;
}
14. 避免使用Exception窗口(Debug|Exceptions)篡改異常處理。
Avoid tampering with exception handling using the Exception window (Debug|Exceptions).
15. 努力對同一邏輯應用程序中(通常是一個解決方案)的所有程序集和客戶端使用統一的版本號。
Strive to use uniform version numbers on all assemblies and clients in the same logical application (typically a solution).
16. Visual Studio.NET應用的配置文件命名爲App.config,並將其包括在項目中。
Name your Visual Studio.NET application configuration file as App.config, and include it in the project.
17. 避免使用顯式代碼來排除方法(#if#endif),而是使用條件方法。
Avoid explicit code exclusion of method calls (#if...#endif). Use conditional methods instead.
public class MyClass
{
[Conditional("MySpecialCondition")]
public void MyMethod()
{}
}
18. 將VS.NET缺省的項目結構改爲標準的佈局,對項目文件夾和文件應用統一的結構。
Modify VS.NET default project structure to your project standard layout, and apply uniform structure for project folders and files.
19. 鏈接一個包含所有解決方案級信息的全局共享文件(圖略)。
Link all solution-wide information to a global shared file:
20. 製表符選用"插入空格",使用3個空格代替製表符。
Insert spaces for tabs. Use 3 spaces instead of tabs。
a) 在工具|選項|文本編輯器|C#|製表符中設置
Tools|Options|Text Editor|C#|Tabs
21. 發佈版中應該包含調試符號。
Release build should contain debug symbols.
22. 總是對程序集簽名,包括客戶端應用程序。
Always sign your assemblies, including the client applications.
23. 總是使用項目的SNK文件對互操作程序集簽名(圖略)。
Always sign interop assemblies with the project''s SNK file

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章