开发者

Conditionally compiling entire namespaces - C#

I was wondering if there is a way to conditionally compile entire namespaces in C#. Or am开发者_StackOverflow中文版 I left with having to explicitly decorate each source file within the namespace with the preprocessor directives to exclude it? In sub-versions of my application the code in various namespace is simply not required and I would like it excluded.

Thanks in advance!


If your namespace is in a separate assembly which doesn't contain anything else you can use the Configuration Manager for your specific sub-version and untick the "Build" check box.

If you've got other classes in the assembly though they will not be built or included obviously, and then the only way would be to decorate with pre-processor declarations.


You would need to put the conditional compilation directive in each file. There is no way to mark an entire namespace as conditionally compiled.

As Michael notes in his answer, a possible solution is to break out the conditional code into a separate project (assembly), and ship that assembly only for configurations that require it; but this will depend on the nature of the conditional code.


You can do this by decorating each file, or you could do it by choosing which files to include. Both MSBuild and csc have options for including all files under a path, and MSBuild additionally has the ability to conditionally include build items based on an attribute (rather than requiring a separate csproj per configuration).

But it is probably easier to decorate the files directly ;-p


I had the same problem, and using directives in each file eventually became too much work; so I started using conditional <ItemGroup> tags in the .csproj file.

For example, if I need to exclude some files from a build, I will move these files into a new <ItemGroup> section...

<ItemGroup Condition=" '$(SlimBuild)' != 'true' ">
...
</ItemGroup>

...and call msbuild.exe with a matching property parameter.

MSBuild.exe MyApp.msbuild /p:Configuration=Release /p:SlimBuild=true

You could probably also use wildcards to include future files.

<ItemGroup>
  <Compile Include=".\SomePath\*.cs" />
</ItemGroup>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜