开发者

What is the .NET attribute to not compile a method in release mode?

I know that if I have a block of code I don't want compiled when in release mode I can wrap that code block in:

#if DEBUG
   while(true)
{ Console.WriteLine("StackOverflow rules"); }
#endif

This will keep this code block from compiling in any mode other than DEBUG.

I know there is an attribute that can be placed on an entire method that will do that same, but for the life of me I can't remember what that attribute is. I believe that it’s down the System.Diagnostics namespace, but I'm not really sure.

BTW: I'm using .NET 4, but I know this attribute existed in .NET 2 because I have used in 开发者_开发技巧in old projects.

Thanks


It's the ConditionalAttribute.

Indicates to compilers that a method call or attribute should be ignored unless a specified conditional compilation symbol is defined.

You should define it as [Conditional("DEBUG")] and make sure that the DEBUG constant is not being defined in release mode.


Alternatively to a ConditionalAttribute you can simply use:

#if (!DEBUG) 


When using the ConditionalAttribute, remember that it cannot be used on functions that return anything other than void or take an out-parameter as argument. A ref-parameter is fine since that variable is instantiated before the method call.

[Conditional("DEBUG")]
public void Success1(string param)

[Conditional("DEBUG")]
public void Success2(ref string param)

[Conditional("DEBUG")] // out parameter
public void CompileErrorCS0685(out string param)

[Conditional("DEBUG")] // non-void function
public bool CompileErrorCS0578(string param)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜