關於測試代碼
有些時候,我們為了測試或者跟蹤某些信息需要編寫一些測試代碼,而這些代碼在正式發行的時候卻是多餘的。那麼我們可以采取以下的方法。1.
#if DEBUG
#endif
2.
[Conditional("DEBUG")]
注意:"DEBUG" 區分大小寫。ConditionalAttribute 需要添加 using System.Diagnostics;
為了檢驗效果,我們看下麵的例子。
public class Class1
{
[Conditional("DEBUG")]
public static void Test()
{
Console.WriteLine("Hello, World!");
}
public static void Main(string[] args)
{
#if DEBUG
Console.WriteLine("Hello, World!");
#endif
Test();
Console.WriteLine("Press Enter key to exit...");
Console.ReadLine();
}
}
{
[Conditional("DEBUG")]
public static void Test()
{
Console.WriteLine("Hello, World!");
}
public static void Main(string[] args)
{
#if DEBUG
Console.WriteLine("Hello, World!");
#endif
Test();
Console.WriteLine("Press Enter key to exit...");
Console.ReadLine();
}
}
我們分別使用Debug和Release模式編譯,然後使用Reflector看看結果。
Debug
----------------
public static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Class1.Test();
Console.WriteLine("Press Enter key to exit...");
Console.ReadLine();
}
{
Console.WriteLine("Hello, World!");
Class1.Test();
Console.WriteLine("Press Enter key to exit...");
Console.ReadLine();
}
Release
----------------
public static void Main(string[] args)
{
Console.WriteLine("Press Enter key to exit...");
Console.ReadLine();
}
{
Console.WriteLine("Press Enter key to exit...");
Console.ReadLine();
}
即便使用ConditionalAttribute,Release模式編譯的目標程序集中依然會有Test方法,隻是調用代碼被編譯器忽略。
最後更新:2017-04-02 00:06:27