- When a method marked as conditional by [Conditional("preprocessing symbol")] is called, the presence or absence of the specified preprocessing symbol determines whether this call is included or omitted. Include the call if the symbol is defined; otherwise omit the call. Using Conditional is an alternative to enclosing #if and #endif inner methods.
#define TRACE_ON //若没有此宏定义预处理,则Trace中的Msg(string msg)方法调用将被忽略
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.");
}
}
If the TRACE_ON identifier is not defined, no trace output will be displayed.
Reference documentation
Conditional (C# Programming Guide)
- The document says that Conditional can achieve the effect of or, but after trying to achieve the effect of and, it doesn't work:
public class Trace
{
[Conditional("TRACE_ON"),Conditional("TRACE_ON_2")] //可以实现或的效果
public static void Msg(string msg)
{
UnityEngine.Debug.Log("msg:" + msg);
}
[Conditional("TRACE_ON")]//可以实现或的效果
[Conditional("TRACE_ON_2")]
public static void Msg2(string msg)
{
UnityEngine.Debug.Log("msg:" + msg);
}
}
The effect of and cannot be achieved in the following way (there is no way to achieve and):
- It has no effect to test the attribute condition of the class, no matter whether DEBUG is defined or not, it has no effect