a) 如果需要編輯機器產生的代碼
b) 盡可能使用分部類來提出需要維護的部分
a) 代碼應該可以自解釋
a) 使用擴展的API文檔說明之
b) 只有在該方法需要被其他的開發者使用的時候才使用方法級的注釋
public class MyClass
{
public readonly int Number;
public MyClass(int someValue)
{
Number = someValue;
}
public const int DaysInWeek =
}
a) 平均每
using System
object GetObject()
{…}
object obj = GetObject()
Debug
catch(Exception exception)
{
MessageBox
throw ; //和throw exception一樣
}
a) 自定義異常要繼承於ApplicationException
b) 提供自定義的序列化功能
//正確方法
public enum Color
{
Red
}
//避免
public enum Color
{
Red =
}
//避免
public enum Color : long
{
Red
}
bool IsEverythingOK()
{…}
//避免
if (IsEverythingOK ())
{…}
//替換方案
bool ok = IsEverythingOK()
if (ok)
{…}
public class MyClass
{}
MyClass[] array = new MyClass[
for(int index =
{
array[index] = new MyClass()
}
Dog dog = new GermanShepherd()
GermanShepherd shepherd = dog as GermanShepherd;
if (shepherd != null )
{…}
a) Copy a delegate to a local variable before publishing to avoid concurrency race
condition
b) 在調用委托之前一定要檢查它是否為null
public class MySource
{
public event EventHandler MyEvent;
public void FireEvent()
{
EventHandler temp = MyEvent;
if(temp != null )
{
temp(this
}
}
}
public class MySource
{
MyDelegate m_SomeEvent ;
public event MyDelegate SomeEvent
{
add
{
m_SomeEvent += value;
}
remove
{
m_SomeEvent
}
}
}
a) 實際情況可能限制為
SomeType obj
IMyInterface obj
/* 假設已有代碼初始化過obj
obj
if (obj
{
obj
}
else
{
//處理錯誤
}
a) 建議使用參數化構造函數
b) 可以重裁操作符
int number = SomeMethod()
switch(number)
{
case
Trace
break;
case
Trace
break;
default :
Debug
break;
}
// 正確使用this的例子
public class MyClass
{
public MyClass(string message )
{}
public MyClass() : this(
{}
}
// 正確使用base的例子
public class Dog
{
public Dog(string name)
{}
virtual public void Bark( int howLong)
{}
}
public class GermanShepherd : Dog
{
public GermanShe pherd(string name)
{}
override public void Bark(int howLong)
{
base
}
}
符替換
class SomeClass
{}
//避免
class MyClass<T>
{
void SomeMethod(T t)
{
object temp = t;
SomeClass obj = (SomeClass)temp;
}
}
// 正確
class MyClass<T> where T : SomeClass
{
void SomeMethod(T t)
{
SomeClass obj = t;
}
}
public class Customer
{…}
//避免
public interface IList<T> where T : Customer
{…}
//正確
public interface ICustomerList : IList<Customer>
{…}
From:http://tw.wingwit.com/Article/program/net/201311/12176.html