根据预处理标识符执行方法。Conditional 特性是 ConditionalAttribute 的别名,可应用于方法或继承自Attribute类的子类。如果应用在其他类上会产生编译错误。
You can use the following techniques to define conditional compilation symbols:
下面3种方式用来定义compilation symbols:
如下面的例子在文件的最开头定义了两个标志,如果把这两行注释掉,则用相应Conditional标记的方法就不会执行:
#define CONDITION1
#define CONDITION2
using System;
using System.Diagnostics;
class Test
{
static
void Main()
{
Console.WriteLine("Calling Method1");
Method1(3);
Console.WriteLine("Calling Method2");
Method2();
Console.WriteLine("Using the Debug class");
Debug.Listeners.Add(new ConsoleTraceListener());
Debug.WriteLine("DEBUG is defined");
}
[Conditional("CONDITION1")]
public
static
void Method1(int x)
{
Console.WriteLine("CONDITION1 is defined");
}
[Conditional("CONDITION1"), Conditional("Condition2")]
public
static
void Method2()
{
Console.WriteLine("CONDITION1 or Condition2 is defined");
}
}
若要获得对符号进行逻辑"与"运算的效果,可以定义序列条件方法。例如,仅当 A 和 B 均已定义时,才能执行下面的第二种方法:
// Code to execute when both A and B are defined...
使用 Conditional 是封闭 #if 和 #endif 内部方法的替代方法,它更整洁、更别致、减少了出错的机会,如下例所示:
Console.WriteLine和Debug.WriteLine的区别:
Console.WriteLine writes to the standard output stream, both in debug and release.
If your purpose of using console.writeline is solely for debugging, you better use debug.writeline.
If you want to show a message to your user, you would use console.writeline.