编译器指令 - 建议 - 仅在调试模式下运行代码
仅当应用程序在调试模式下运行时,我才需要记录消息。我找到了两种方法:
第一种:需要日志记录时,需要到处写3行。但是,Logger 语句仅在编译时被禁用,这正是我所需要的。 Logger.Log根本不会被执行。
#if DEV_ENV
Logger.Log("Application started !"); // This line is grayed. Perfect !
#endif
public static void Log(string message)
{
Debug.WriteLine(message);
}
第二:非常整洁。需要记录的地方只需一行代码。不确定Logger.Log语句是否被执行。 如果仅在编译时删除函数调用(与第一种方法相同。但是,现在确定代码行没有变灰),我想继续这样做。
Logger.Log("Application started !"); // This line is not grayed out. But, function is not called. So, confused whether its removed at compile time.
[Conditional("DEV_ENV")]
public static void Log(string message)
{
Debug.WriteLine(message);
}
我担心性能差异。
I need to Log messages only when application is running in debug mode. I have found 2 ways:
First: Need to write 3 lines everywhere when logging is needed. But, Logger statement is disabled at compile time only which is exactly I need. Logger.Log will not be executed at all.
#if DEV_ENV
Logger.Log("Application started !"); // This line is grayed. Perfect !
#endif
public static void Log(string message)
{
Debug.WriteLine(message);
}
Second: Very neat. Only one line of code wherever logging is required. Not sure, whether Logger.Log statement is executed or not. If function call is removed at compile time only (same as first approach. But, now sure as line of code is not greyed out), I want to go with this.
Logger.Log("Application started !"); // This line is not grayed out. But, function is not called. So, confused whether its removed at compile time.
[Conditional("DEV_ENV")]
public static void Log(string message)
{
Debug.WriteLine(message);
}
I am concerned about the performance differences.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从 MSDN 页面获取 ConditionalAttribute:
因此,正如它所说,方法调用在编译时被删除,与
#if
相同。From the MSDN page for the ConditionalAttribute:
So, as it says, the method call is removed at compile time, same as the
#if
.根据您的编译设置,您可以使用:
或者,
Depending on your compile settings, you could use:
or,
正如 George 指出的那样,如果应用了 Conditional 属性,则不会编译方法调用。这也意味着(与直接使用
#If DEV_ENV
删除代码一样),方法调用中包含的任何副作用也不会发生 - 与往常一样,有关记录代码中存在副作用的警告是很好的成立:如果未定义
SKIP
,则此代码将打印92
。如果定义了SKIP
,则会打印92变为93
和93
。As George points out, the method call will not be compiled if the Conditional attribute is applied. This also means (as with removing the code directly using
#If DEV_ENV
) that any side effects included in the method call will also not occur - as always, the warning about having side effects in logging code are well founded:If
SKIP
is not defined, this code prints out92
. IfSKIP
is defined, it prints92 became 93
and93
.