根据预处理标识符执行方法。Conditional
属性是 ConditionalAttribute 的别名,可应用于方法或属性类。
在本示例中,Conditional
应用于方法以启用或禁用程序特定的诊断信息的显示:
| 复制代码 |
---|
#define TRACE_ON
using System;
using System.Diagnostics;
public class Trace
{
[Conditional("TRACE_ON")]
public static void Msg(string msg)
{
Console.WriteLine(msg);
}
}
public class ProgramClass
{
static void Main()
{
Trace.Msg("Now in Main...");
Console.WriteLine("Done.");
}
} |
如果未定义 TRACE_ON
标识符,则将不会显示跟踪输出。
Conditional
属性经常与 DEBUG
标识符一起使用以启用调试版本的跟踪和日志记录功能(在发布版本中没有这两种功能),如下例所示:
| 复制代码 |
---|
[Conditional("DEBUG")]
static void DebugMethod()
{
} |
备注
使用多个标识符
如果某个方法具有多个 Conditional 属性,且至少定义了多个条件符号(换言之,这些符号彼此之间存在逻辑“或”关系)中的一个,则将包含对该方法的调用。在本例中,A
或 B
的存在将导致方法调用:
C# | 复制代码 |
---|
[Conditional("A"), Conditional("B")]
static void DoIfAorB()
{
// ...
}
|
若要获得对符号进行逻辑“与”运算的效果,可以定义序列条件方法。例如,仅当 A
和 B
均已定义时,才能执行下面的第二种方法:
C# | 复制代码 |
---|
[Conditional("A")]
static void DoIfA()
{
DoIfAandB();
}
[Conditional("B")]
static void DoIfAandB()
{
// Code to execute when both A and B are defined...
}
|
使用具有属性类的条件
Conditional 属性还可被应用于属性类定义。在本例中,仅当定义了 DEBUG 时,自定义属性 Documentation
才向元数据添加信息。
C# | 复制代码 |
---|
[Conditional("DEBUG")]
public class Documentation : System.Attribute
{
string text;
public Documentation(string text)
{
this.text = text;
}
}
class SampleClass
{
// This attribute will only be included if DEBUG is defined.
[Documentation("This method displays an integer.")]
static void DoWork(int i)
{
System.Console.WriteLine(i.ToString());
}
}
|
请参见