在引用的程序条件编译条件、程序

2023-09-05 23:47:13 作者:玩世不恭

我正在写一个程序集与一些在里面条件编译成员,如:

I'm writing an assembly with some conditionally compiled members in it, e.g.:

[Conditional("DEBUG")]
public static void Log(string message) { /*...*/ }

和使用它像这样:

public void DoStuff() {
    Log("This will only appear on debug builds");
    /* ... Do stuff ... */
}

但是,当我把这个集会的人在自己的项目中使用,我希望他们能够确定与否DEBUG-条件的成员进行编译。

But when I give this assembly to someone to use in their project, I want them to be able to define whether or not DEBUG-conditional members are compiled.

如果这是不可能的(如方法只是完全在编译时去掉),那么有没有什么办法可以打包组件的多个配置(例如可能与 [AssemblyConfiguration] ),并选择他们根据引用组件的配置?

If that's not possible (e.g. the methods are just completely removed at compile-time), then is there any way to package multiple 'configurations' of an assembly (e.g. maybe with [AssemblyConfiguration]) and select them according to the configuration of the referencing assembly?

另外:我不是在寻找的建议手动设置在引用组件的.csproj的文件中引用;我知道我能做到这一点,但它的繁琐,并为每一位参考做。

Also: I'm not looking for suggestions to manually set the references in the .csproj file of the referencing assembly; I know I can do that, but it's tedious, and has to be done for every reference.

推荐答案

该方法会被编译成汇编独立的定义值,所以你可以使用的方法和方法的使用将取决于编译器在编译客户端时定义装配。

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.

在换句话说,System.Diagnostics.ConditionalAttribute指示,该方法调用应该忽略的编译器,而不是如何该方法被编译

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