条件编译 - 逐步淘汰 C# 中的部分代码
我正在开发一个项目,需要为项目的一个阶段设计和使用一组类。
在后续阶段,我们将不需要这组类和方法。这些类和方法集将在整个应用程序中使用,因此如果我将它们添加为任何其他类,则在不需要它们时我需要手动删除它们。
C# 中有没有一种方法,以便我可以在类上或类实例化的位置设置属性,以避免基于属性值的实例化和方法调用。
就像设置
[Phase = 2]
BridgingComponent bridgeComponent = new BridgeComponent();
在这方面的任何帮助表示赞赏。
I'm working on a project, where I need a set of classes to be designed and used for one phase of the project.
In the subsequent phase, we will not be needing the set of classes and methods. These set of classes and methods will be used throughout the application and so if I add them as any other classes, I would need to manually remove them once they are not required.
Is there a way in C#, so that I can set an attribute on the class or places where the class is instantiated, to avoid that instantiation and method calls based on the value of the attribute.
Something like, setting
[Phase = 2]
BridgingComponent bridgeComponent = new BridgeComponent();
Any help appreciated on this front.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 Properties>build 例如 PHASE1
和代码中设置编译标志
Set a compilation flag in Properties>build e.g. PHASE1
and in the code
您还可以使用依赖注入框架,如 Spring.NET、NInject 等。另一种方法是使用工厂方法来实例化您的类。然后,您将拥有用于 Phase1、Phase2 等的工厂类。在后一种情况下,您可以选择运行时而不是编译时。
You could also use a dependency injection framework like Spring.NET, NInject, etc. Another way is to use factory methods to instantiate your classes. You will then have a factory class for Phase1, for Phase2, etc. In the latter case you have run-time selection instead of compile time.
关于方法,您可以使用 Conditional 属性:
好处是,如果未定义符号,则不会编译方法调用。
About methods, you can use the Conditional attribute:
The good thing is that if the symbol is not defined, the method calls are not compiled.
当 C# 编译器遇到 #if 指令 时,最终会出现#endif指令,仅当定义了指定符号时才会编译指令之间的代码。
When the C# compiler encounters an #if directive, followed eventually by an #endif directive, it will compile the code between the directives only if the specified symbol is defined.
听起来您正在要求 #if。
然后,当您希望将 BridgingComponent 包含在构建中时,请在编译行上使用
/define Phase2
,而当您不希望包含时则不要使用。Sounds like you're asking for #if.
And then use a
/define Phase2
on the compile line when you want BridgingComponent included in the build, and don't when you don't.