--------------------------http://ahupc.cnblogs.com/archive/2006/04/29/388343.html
"没有规矩,不成方圆",C#是.net中一个功能强大的语言,这意味着你用C#可以编写强大的程序,也可以产生一堆垃圾,在你没有自信成为绝顶的高手、轻松驾驭C#这匹野马之前,遵循一定的编程规范和标准起码可以让你和你的团队轻松交流,并且和他们看起来保持同一个水平。规范可以一定程度上保证软件质量、保证项目进度,其重要性就不在罗嗦。我认为任何一个程序员在开始动手一个项目之前,都应该仔细阅读一下公司相关方面的标准和规范,这里转一篇老文,是IDesign C#编程规范,小鸡射手翻译,我稍稍整理了一下,你也可以下载E文PDF文件。
目录内容如下:
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
一、命名规则和风格
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");
};
二、编码惯例
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.
三、项目设置和项目结构
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"?>
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
四、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.
本文转自kenty博客园博客,原文链接http://www.cnblogs.com/kentyshang/archive/2006/06/13/424756.html如需转载请自行联系原作者
kenty