问题描述
我知道我可以在 C#
中使用预处理器指令来启用/禁用部分代码的编译。
I know that I can use preprocessor directives in C#
to enable/disable compilation of some part of code.
如果我在同一文件中定义指令,则可以正常工作:
If I define a directive in the same file, it works fine:
#define LINQ_ENABLED
using System;
using System.Collections.Generic;
#if LINQ_ENABLED
using System.Linq;
#endif
现在,我用在 C ++
将所有这些配置指令放在单个头文件中,并将其包含在需要这些指令的所有文件中。
Now, I'm used in C++
at putting all this configuration directives inside a single header file, and include it in all files where I need such directives.
如果我执行相同的操作在 C#
中不起作用:
If I do the same in C#
something doesn't work:
//Config.cs
#define LINQ_ENABLED
//MyClass.cs
#define LINQ_ENABLED
using System;
using System.Collections.Generic;
#if LINQ_ENABLED
using System.Linq;
#endif
我也尝试了以下操作,但似乎无法定义指令在命名空间内:
I also tried the following but seems that I can't define a directive inside a namespace:
//Config.cs
namespace Conf{
#define LINQ_ENABLED
}
//MyClass.cs
#define LINQ_ENABLED
using System;
using System.Collections.Generic;
using Conf;
#if LINQ_ENABLED
using System.Linq;
#endif
- 我在做什么错了?
- 在
C#
中的不同文件中使用预处理器的正确方法是什么? - 有什么更好的方法吗?
- What am I doing wrong?
- What's the right way of using preprocessor across different files in
C#
? - Is there any better way to do that?
推荐答案
.csproj中有一个部分:
In your .csproj there is a section:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DefineConstants>TRACE;DEBUG;LINQ</DefineConstants>
</PropertyGroup>
</Project>
如果需要额外的预处理器,可以在其中添加它们。
If you want extra preprocessors you can add them there.
或通过项目的属性将自动为您添加它们。在构建标签下的属性中。
Or via the properties of the project which will add them there automatically for you. In properties under the Build tab.
这篇关于C#中跨不同文件的预处理器指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!