Conditional Compilation in Referenced Assemblies

为君一笑 提交于 2019-12-04 07:22:22

[Conditional("DEBUG")] is exactly what you are looking for. MSDN explanation of that attribute says:

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

However, what that explanation (as well as many others) fails to mention is that compilation symbol in question needs to be defined in the referencing assembly. In other words, if Assembly A contains method

[Conditional("DEBUG")]
public static void SomeMethod()
{ /* ... */ }

and you compile that assembly as Release, then SomeMethod will get called from Assembly B as long as that assembly is compiled as Debug.

The methods will be compiled into assembly independently of the defined values, so you can use the methods, and method usage will depend on the compiler defines when compiling the client assembly.

In other words, System.Diagnostics.ConditionalAttribute instructs the compiler that the METHOD CALL should be ignored, not how the method is compiled.

Method calls will be removed at compile time when some other code tries to use the method.

So depending on your goals you can either:

  • If you want others to conditionally use your "Log" method, but your own code in that assembly should not use the method - give release assembly (one compiled without "DEBUG").
  • If you want others to conditionally use your "Log" and your own code to log too - give debug assembly
  • If you want to be able to turn on/off logging for your own code at run time - consider using actual logging framework that allows it (even one that is part of .Net framework let you do so).

For more info check ConditionalAttribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!