IDesign发布了c#编程规范,小鸡射手从only4gurus下载浏览后决心抽时间翻译一下,以更好地学习。
目录内容如下:
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 ?white 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 ?base?
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
4 Framework特别指导
Framework Specific Guidelines
4.1 数据访问
Data Access
1. 总是使用类型安全的数据集或者数据表。避免使用原始的ADO.NET。
Always use type-safe data sets or data tables . Avoid raw ADO.NET.
2. 访问数据库时总是使用事务。
Always use transactions when accessing a database.
a) 总是使用服务组件事务。
Always use Enterprise Services transactions.
b) 不要使用ADO.NET事务。
Do not use ADO.NET transactions.
3. 总是将事务隔离级别设置为序列的。
Always use transaction isolation level set to Serializable.
a) 使用其它隔离级别需要管理层决定。
Requires management decision to use anything else.
4. 不要使用服务器浏览器将数据库连接拖到Windows表单、ASP.NET表单或Web服务中。这样做耦合了界面层和数据层。
Do not use the Server Explorer to drop connections on windows forms, ASP.NET forms or web services. Doing so couples the presentation tier to the data tier.
5. 避免使用SQL Server验证。
Avoid SQL Server authentication.
a) 而是使用Windows验证。
Use Windows authentication instead.
6. 将访问SQL Server的组件以调用该组件客户端不同的身份运行。
Run components accessing SQL Server under separate identity from that of the calling client.
7. 总是在高层用类型安全的类包装存储过程。仅在那个类中调用存储过程。
Always wrap your stored procedures in a high level, type safe class. Only that class invokes the stored procedures.
8. 避免在存储过程中放任何逻辑。
Avoid putting any logic inside a stored procedure.
a) 如果存储过程中有IF,你可能犯了错误。
If there is an IF inside a stored procedure, you are doing something wrong.
目录内容如下:
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 ?white 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 ?base?
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
4 Framework特别指导
Framework Specific Guidelines
4.1 数据访问
Data Access
1. 总是使用类型安全的数据集或者数据表。避免使用原始的ADO.NET。
Always use type-safe data sets or data tables . Avoid raw ADO.NET.
2. 访问数据库时总是使用事务。
Always use transactions when accessing a database.
a) 总是使用服务组件事务。
Always use Enterprise Services transactions.
b) 不要使用ADO.NET事务。
Do not use ADO.NET transactions.
3. 总是将事务隔离级别设置为序列的。
Always use transaction isolation level set to Serializable.
a) 使用其它隔离级别需要管理层决定。
Requires management decision to use anything else.
4. 不要使用服务器浏览器将数据库连接拖到Windows表单、ASP.NET表单或Web服务中。这样做耦合了界面层和数据层。
Do not use the Server Explorer to drop connections on windows forms, ASP.NET forms or web services. Doing so couples the presentation tier to the data tier.
5. 避免使用SQL Server验证。
Avoid SQL Server authentication.
a) 而是使用Windows验证。
Use Windows authentication instead.
6. 将访问SQL Server的组件以调用该组件客户端不同的身份运行。
Run components accessing SQL Server under separate identity from that of the calling client.
7. 总是在高层用类型安全的类包装存储过程。仅在那个类中调用存储过程。
Always wrap your stored procedures in a high level, type safe class. Only that class invokes the stored procedures.
8. 避免在存储过程中放任何逻辑。
Avoid putting any logic inside a stored procedure.
a) 如果存储过程中有IF,你可能犯了错误。
If there is an IF inside a stored procedure, you are doing something wrong.