预处理命令之条件编译(转)
我初学.NET 时通常会这样写条件编译:
/// <summary>
/// 不推荐的条件编译方法
/// </summary>
public void CheckData(object o)
{
# if DEBUG
//Do Some
#endif
}
其实.net 框架提供了条件编译的良好方法,推荐写法:
/// <summary>
/// 定义一个方法的条件编译,推荐方式
/// </summary>
[Conditional("Debug")]
public void CheckData()
{
//Todo check
}
如果是不是方法级别的条件编译,我们的写法又回归了:
public void CheckData<T>(List<T> list)
{
try
{
//Do something
}
catch (Exception ex)
{
logger.InfoFormat(ex.Message);
# if DEBUG
throw new AbnormalDataException(String.Format("新增记录异常{0}", ex.Message), ex);
#else
throw new AbnormalDataException("新增记录异常",ex);
#endif
}
}
备注:
1.标识符 Debug #DEBUG 区分大小写
2.善用Conditional ,拆分Simple Method
**********************************************
还有这样的文章:
http://www.cnblogs.com/iimax/archive/2009/03/16/1413257.html
http://www.cnblogs.com/kane_zzt/archive/2008/12/03/1346556.html
http://www.cnblogs.com/thinhunan/archive/2005/04/18/139518.html
http://www.cnblogs.com/piccolo/articles/250707.html
http://www.cnblogs.com/blognetspace/archive/2009/02/12/1388943.html
http://www.cnblogs.com/muddle/archive/2004/04/07/5402.html
http://www.cnblogs.com/zhangaz1/articles/1175800.html