0

Can I write in code to set the variable to true or false depending on a button I pressed? See example below.

If not, what other ways are there to achieve similar effects? I have already marked the codes for different modes using directives and only want developers to have the option of switching the modes, but now I wish to give the user the option of switching between the modes. The choice of the mode will only be given at the start of the program, and user is not allowed to switch the mode. To switch the mode, he can only restart the program again.

If cannot use directives, what is the fastest way can I use? (note: the statements are all around the solution)

In pseduocode of what I wish to achieve:

void button_click(...){
    if(!CONDITION)
        CONDITION = true;
    else
        CONDITION = false;
}


...
#if CONDITION
   //mode X with addtional steps
#endif
4

7 回答 7

5

您正在使用预处理器指令并尝试从违背目的的代码中设置它,即使它是可能的(我很确定你不能)。为什么不使用常规布尔字段作为标志?

private bool Condition {get; set;}
于 2011-04-12T17:19:35.503 回答
2

这是不可能的。if 语句在运行时执行,但预处理器指令如#IF在编译时执行。您需要在编译时决定如何构建代码,并在项目中的某个位置(例如在项目的属性中)或源文件的顶部,设置CONDITION为给定构建所需的任何内容。

如果这确实需要成为运行时决策,那么您需要包含所有可能的代码路径并在运行时决定采用哪一个。

于 2011-04-12T17:21:08.053 回答
0

这些指令提供有条件地跳过源文件部分、报告错误和警告条件以及描绘源代码的不同区域的能力。您不能在运行时更改它们。

于 2011-04-12T17:25:16.517 回答
0

如果您询问是否可以根据代码中的条件有条件地编译某些东西,答案是否定的。编译器必须在编译时知道要在程序集中包含什么。您几乎可以肯定地在没有条件编译的情况下实现您正在尝试的内容,但是您正在尝试做什么?

于 2011-04-12T17:20:16.783 回答
0

'#IF' 指令用于条件编译,这意味着它会查找在编译时定义的标记并逐字编译或不编译特定代码。这意味着未编译的代码不是程序的一部分,不能在运行时使用。如果您想在运行时更改行为,则需要修改代码以使用普通标志而不是条件编译。也就是说,您可能需要考虑进行更深入的设计审查,因为基于配置标志添加新的分支功能会很快导致代码混乱。

于 2011-04-12T17:21:24.817 回答
0

#IF指令是一个预处理器选项,一旦编译代码就没有任何意义,因此您不能在编译后使用它们来控制程序流。

至于您的其他选项,您应该能够相当容易地将它们转换为类级别的变量,但是从消极的一面来看,您的代码将充满可能最终难以管理的if CONDITION ... else ...语句。

另一个对 OOP 更友好的选择是实现状态模式。您可以将每个“条件”的行为封装到它自己的状态中,并在模式中在它们之间切换。这对于两个州来说可能是过度的(很可能是)。

另一个参考: http: //www.dofactory.com/Patterns/PatternState.aspx

于 2011-04-12T17:43:11.253 回答
0

#IF是在编译时确定的,您想在运行时更改它。是不可能的。

于 2018-12-10T22:04:14.073 回答