简体   繁体   English

有没有一种方法可以在C#中在运行时分配条件方法或添加preprosessor指令?

[英]Is there a way to assign conditional methods or add preprosessor directives at run-time in C#?

目的是能够在运行时从生产构建中的数据库切换调试调用。

No; 没有; the point of conditional methods and preprocessor directives is that they cause the compiler to omit code from the final executable. 条件方法和预处理器指令的要点是它们使编译器忽略最终可执行文件中的代码。 The runtime equivalent of these is an if statement. 与运行时等效的是if语句。

However, aspect-orientated programming is roughly equivalent to what you're asking, in that it allows you to inject code into a running program that wouldn't otherwise be there. 但是, 面向方面的编程大致上与您所要求的相同,因为它使您可以将代码注入正在运行的程序中,否则该程序将不存在。

Edit: as Joe mentioned, the way to do this is to program against a logging framework like log4net that allows fine-grained control over what gets logged. 编辑:正如Joe所提到的,执行此操作的方法是针对log4net之类的日志记录框架进行编程,该框架允许对所记录的内容进行细粒度的控制。

Not at the pre-processor level. 不在预处理器级别。 After all, you're running the result of that process. 毕竟,您正在运行该过程的结果。 Of course, you could change your pre-processor checks to be normal code checks, which can obviously be switched as required. 当然,您可以将预处理程序检查更改为常规代码检查,显然可以根据需要进行切换。

No, but most logging subsystems provide this ability. 不可以,但是大多数日志子系统都提供此功能。 Eg with log4net you can change the logging level dynamically, or if using System.Diagnostics.Trace you can change the TraceSwitch level dynamically. 例如,使用log4net可以动态更改日志记录级别,如果使用System.Diagnostics.Trace,则可以动态更改TraceSwitch级别。

You obviously can't affect the binary code as such (as with the #if statement). 您显然不能这样影响二进制代码(例如#if语句)。

What I usually do is to make sure that my code contains a lot of logging, that is activated by trace switches . 我通常要做的是确保我的代码包含大量的日志记录,这些记录由跟踪开关激活。 That way you can have a system run in production with little or no logging, and when you want to research some problem you can switch logging on by altering the config file. 这样一来,您就可以在几乎没有日志记录的情况下在生产环境中运行系统,并且当您要研究某些问题时,可以通过更改配置文件来打开日志记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM