c# 条件编译 Conditional ("DEBUG")
简而言之:可以通过Conditional 指定函数和属性是否编译到最终产品中去。同时还应该看看 AttributeUsage Obsolete
C# Language Specification
System.AttributeUsageAttribute(Section 17.4.1), which is used to describe the ways in which an attribute class can be used.System.Diagnostics.ConditionalAttribute(Section 17.4.2), which is used to define conditional methods.System.ObsoleteAttribute(Section 17.4.3), which is used to mark a member as obsolete.
利用 Conditional 属性,程序员可以定义条件方法。Conditional 属性通过测试条件编译符号来确定适用的条件。当运行到一个条件方法调用时,是否执行该调用,要根据出现该
调用时是否已定义了此符号来确定。如果定义了此符号,则执行该调用;否则省略该调用(包括对调用的参数的计算)。
条件方法要受到以下限制:
条件方法必须是类声明或结构声明中的方法。如果在接口声明中的方法上指定 Conditional 属性,将出现编译时错误。
条件方法必须具有 void 返回类型。
不能用 override 修饰符标记条件方法。但是,可以用 virtual 修饰符标记条件方法。此类方法的重写方法隐含为有条件的方法,而且不能用 Conditional 属性显式标记。
条件方法不能是接口方法的实现。否则将发生编译时错误。
A conditional method is subject to the following restrictions:
- The conditional method must be a method in a class or struct declaration. A compile-time error occurs if the
Conditionalattribute is specified on a method in an interface declaration. - The conditional method must have a return type of
void. - The conditional method must not be marked with the
overridemodifier. A conditional method may be marked with thevirtualmodifier, however. Overrides of such a method are implicitly conditional, and must not be explicitly marked with aConditionalattribute. - The conditional method must not be an implementation of an interface method. Otherwise, a compile-time error occurs.
//z 2012-2-24 17:47:38 PM is2120@csdn
示例1:
// CondMethod.cs
// compile with: /target:library /d:DEBUG
using System;
using System.Diagnostics;
namespace TraceFunctions
{
public class Trace
{
[Conditional("DEBUG")]
public static void Message(string traceMessage)
{
Console.WriteLine("[TRACE] - " + traceMessage);
}
}
}
示例2:
using System;
using System.Diagnostics; |
public classTrace |
{ |
[Conditional("DEBUG")] |
publicStaticvoidShowMessage(stringmsg) |
{ |
Console.WriteLine(" [Trace - "+ msg); |
} |
} |
public classProgram |
{ |
publicstaticvoidMain() |
{ |
Trace.ShowMessage("Starting"); |
Console.WriteLine("运行中"); |
Trace.ShowMessage("Ending"); |
} |
}//z 2012-2-24 17:47:38 PM is2120@csdn