.NET 编码最佳实践






2.58/5 (27投票s)
.NET 编码最佳实践 - Vinayak 的经验法则不要硬编码字符串/数字。 而是使用常量,如下所示。不良实践 int Count; Count = 100; if( Count == 0 ) { // 执行某些操作… }良好实践 int Count; Count = 100; private...
.NET 编码最佳实践 - Vinayak 的经验法则
- 不要硬编码字符串/数字。 而是使用常量,如下所示。 不良实践
int Count; Count = 100; if( Count == 0 ) { // DO something… }
良好实践int Count; Count = 100; private static const int ZERO = 0; if( Count == ZERO ) { // DO something… }
- 对于字符串比较 - 使用 String.Empty 代替 “”
- 默认情况下,将成员变量的作用域设置为“private”,根据需要将其扩展到 protected、public 或 internal。
- 默认使作用域为 private 的另一个优势是,在 XMLSerilaization 期间,它默认会序列化所有公共成员。
- 当需要在循环内操作字符串时,使用 StringBuilder 代替 string,如下所示。 不良实践
String temp = String.Empty; for( int I = 0 ; I<= 100; i++) { Temp += i.ToString(); }
良好实践StringBuilder sb = new StringBuilder(); for ( int I = 0 ; I<= 100; i++) { sb.Append(i.ToString()); }
- 对于简单操作,优先使用数组而不是集合。
- 优先使用泛型集合而不是 ArrayList
- 优先使用泛型字典而不是 HashTable *。
- 对于字符串操作和存储,优先使用 StringCollections 和 StringDictionaries。
- 使用适当的数据类型。 例如:如果您想检查任何状态,请优先使用 bool 而不是 int。 不良实践
int Check = 0; if(Check == 0) { // DO something }
良好实践bool Check = false; if(!Check) { // DO something }
- 使用“as”运算符进行类型转换,并在使用结果值之前检查是否为 null。
class A { } class B : A { } B objB = new B(); A objA1 = (A) objB; A objA 2 = objB as A; if( objA2 != null) { //Do something }
- 对于 WCF 代理创建,使用 using 语句
using(Cerate the proxy) { //Do the required operation }
- 遵循“晚获取,早释放”规则,对于昂贵的资源,例如连接、文件等。 例如:如果您想对任何数据操作使用 SqlConnection 对象,请在方法级别而不是类级别创建实例。
class MyData { public MyData() { } public List
如果您想在类级别创建 SqlConnection 实例,请确保为该类实现 IDisposable,并在 Dispose(); 中清理 SqlConnection 实例。GetAllCustomer() { using(SqlConnection objConnection = new SqlConnection(“Connection string”)) { //Do the operation and get the required data.. } } } class MyData : IDisposable { SqlConnection objConnection = default(SqlCOnnection); public MyData(){ objConnection = new SqlCOnnection(“Connection string”); } public List
GetAllCustomer(){ // By using objConnection get the required data } public void Dispose(){ // Do the cleanup of SqlCOnnection if( objConnection != null ){ if( objConnection.State == ConnectionState.Open){ objConnection.Close(); } } } } - 如果您不希望任何人扩展您的类功能,请将其设为“sealed”,以获得内联和编译时优势
- 避免为每个类声明“析构函数”。 这会增加类的生命周期,不必要地使其存活时间过长
- 优先使用线程池而不是手动线程。
- 不要在循环中调用任何方法。 例如:不良实践
for( int i = 0; i<= 100; i++) { Calculate(i); }
良好实践for( int i = 0; i<= 100; i++) { //Inline the body of Calculate. }
- 不要在循环内处理异常,而是在 try/catch 中处理循环逻辑。 例如:不良实践
for(int i = 0 ; i<= 100; i++){ try{ } catch(Exception ex){ throw ex; } }
良好实践try{ for(int i = 0 ; i<= 100; i++){ } } catch(Exception ex){ throw ex; }
- 不要使用 Exception 处理应用程序逻辑。 例如:不良实践
try{ int x,y,z; x = 0; y = 10; z = y/x; } catch(DevideByZeroException ex){ throw ex; }
良好实践private static const int ZERO = 0; try{ int x,y,z; x = 0; y = 10; if( x != ZERO){ z = y/x; } } catch(Exception ex){ }
- 优先使用 for/while 循环而不是 foreach
- 对于层之间的通信,优先使用数据传输对象而不是 DataSet/DataTables。