开发者

Is it possible to disable a function in C#

In my program I have function to create log. Insid开发者_Go百科e the function I check if a variable is true to continue its working or not.

private void log(string text)
{
    if(LOGGING_ENABLED)
        logtextbox.Text = text;
}

Is there any way to disable a function outside, without using any if inside the function or in parameter, to disable all occurrences of function in program.


You can use the ConditionalAttribute. Calls to a method with this attribute are compiled out depending on whether the condition is defined. For example:

[Conditional("DEBUG")]
private void log(string text){
   logtextbox.Text = text;
}

Calls to this method will show up in Debug mode, but will not be in your code in Release mode, because the DEBUG condition is only defined during Debug mode.

Edit: In response to some of your questions, I'd recommend taking a look at the API Reference page. It has some pretty simple examples and explanations on how to use the attribute and its effects.


You could use conditional compilation like so:

private void log(string text)
{
  #if DEBUG
    logtextbox.Text = text;
  #endif
}

Using this, your log method would only log do it's work when your project is compiled in DEBUG-mode inside Visual Studio.


The only way to disable the method even being called, would be by using preprocessor directives, as others have mentioned. You can do this also by using an attribute:

[Conditional("DEBUG")]
private void log(string text)
{
    logtextbox.Text = text;
}


If you use it only for debug purpose you can use [ConditionalAttribute("DEBUG")] attribute on top of function, or you can use #if/#endif precompiled dirrectives to sign your code that will run only if specified condition is signed before compilation. For example, to remove completely the function from release build you can do something like this.

#if DEBUG
private void log(string text)
{
    if(LOGGING_ENABLED)
        logtextbox.Text = text;
}
#endif

The thing is to keep in mind that the same #if/#endif has to be applied to all calls of this method in this case.


in fact your example is a bit simple because you want to disable log to user interface and this is probably local to that form and not application wide.

what usually is done with logging engines, like NLog and Log4Net or any other one is using configuration to control how much and how logging is performed.

for example there is a concept of log level, if you have it set for FATAL only fatal errors are logged, if you set it to ALL everything is logged, including info and verbose logs.

those frameworks also have configurable appenders in thea pp.config or web.config files so you can simply add or disable certain appenders depending on your needs (like RollingFile appender, SMTPAppender, EventLogAppender and many others...)


You can throw a NotSupportedException, mark it as Obsolete and use EditorBrowsable:

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜