使用 C# 预处理器添加引用
我有一个可以通过命令行构建的大型应用程序。 我想指定一个标志,使我能够将其编译为两种模式之一:实际模式或模拟模式。
所以主要问题是,如何使用预处理器以编程方式添加引用?
例如:
#if SIMULATED
include SimulatedFiles;
myFactory = new SimulatedFiles.simFactory();
#else
myFactory = new realFactory();
#endif
我不希望将任何模拟文件编译到我的“实际”应用程序中。 由于 C# 中没有“include”指令,我一直不知道如何实现这一点。
I have a large application that I can build through the command line. I want to specify a flag that enables me to compile it into either one of two modes, Actual or Simulated.
So the main issue is, how can I use the preprocessor to programmatically add a reference?
For example:
#if SIMULATED
include SimulatedFiles;
myFactory = new SimulatedFiles.simFactory();
#else
myFactory = new realFactory();
#endif
I don't want any simulated files to compiled into my "actual" application. Since there is no "include" directive in C#, I am stuck on how to accomplish this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C# 中,没有真正的预处理器,您可以在 C# 预处理器文档。
从文档(强调我的):
In C#, there is no real preprocessor, as you can read on the C# Preprocessor's documentation.
From the documentation (emphasis mine):
nant/msbuild 和带有 xml 配置的依赖注入工具?
nant/msbuild and dependency injection tool with xml configuration?
您无法通过 C# 预处理器语句执行此操作,因为该语言不支持通过预处理器宏进行引用的概念。
您可以做的是使用 msbuild 文件并更改基于 msbuild 参数添加的引用集。
You cannot do this via a C# preprocessor statement because the language doesn't support the notion of references via preprocessor macros.
What you can do is use a msbuild file and alter the set of references added based on msbuild parameters.
包含文件是您自己的源代码还是第三方程序集 dll?
如果它们是您自己的源,那么您可以轻松地使用条件编译从发布版本中删除“模拟”代码,就像您在示例中所做的那样(只需将“include”替换为“using”)。 例如,这是调试类的常见做法。
如果您不“控制”包含的源代码,那么您仍然可以添加项目引用,但如果您有条件地编译使用该程序集的所有代码,您的应用程序将永远不会尝试访问该程序集,因此当代码运行时它不需要存在。
(另一种对您来说似乎不太有用的可能性是编写您所提供的引用程序集的“虚拟”版本来代替“真实”程序集,或者仅在模拟构建中调用真正的第三方 dll 的代理。如果它提供您调用的公共类和方法,您可以将虚拟程序而不是模拟程序集发送给客户)
Are the include files your own source code, or third-party assembly dlls?
If they are your own sources, then you can easily use conditional compilation to remove the "simulated" code from your release build, exactly as you have done in your example (just replace 'include' with 'using'). This is common practice with debugging classes for example.
If you don't "control" the source code for the includes, then you can still add a project reference, but if you conditionally compile all the code that uses the assembly, your applicaton won't ever attempt to access the assembly, so it doesn't need to be be present when the code is running.
(Another possiblity that seems less useful for you is to write a "dummy" version of the referenced assembly that you ship in place of the "real" one, or a proxy that calls the real third-party dll in simulated builds only. If it supplies the public classes and methods that you call, you can ship the dummy instead of the simulated assembly to your customers)