【问题标题】:Editing booleans from another class in an array编辑数组中另一个类的布尔值
【发布时间】:2017-04-06 04:35:36
【问题描述】:

这可能是一个菜鸟问题,但我被困住了。

我这里有我表单中的代码。这是我分配给按钮的事件。
这些按钮应该在SomeClass 中切换booleans 的状态。

这些布尔值都是public static bool boolA 等。

这是我的表单代码。

    public void switchButton(object sender, EventArgs e)
    {
        Button[] buttons = { btnA, btnB };
        bool[] bools = { SomeClass.boolA, SomeClass.boolB };

        Button button = (Button)sender;
        int index = Array.IndexOf(buttons, button);


        if (bools[index])
        {
            bools[index] = false;
            button.Text = "Start";
        }
        else
        {
            bools[index] = true;
            button.Text = "Stop";
        }
    }

发生的情况是,当我再次单击按钮时,按钮的文本设置为“停止”,但永远不会设置为“开始”。

非常感谢您的帮助。

【问题讨论】:

  • if (boools[index]) 只是在这段代码中有一个 o 吗?
  • bools 每次单击按钮时都会重新定义
  • @Liam 没关系,因为 SomeClass.boolA, boolB 是静态字段
  • 如果您不使用数组,这一切都会容易得多。为什么不直接设置boolAboolB
  • @MadOX:这很重要,因为数组包含值的副本

标签: c# arrays class boolean


【解决方案1】:

boolvalue type。它们在.Net 中是原子的。因此,当您将它们分配给新变量时,它们会被复制。所以在:

bool[] bools = { SomeClass.boolA, SomeClass.boolB };

bools[0] 存在于一个内存地址中,而SomeClass.boolA 存在于另一个内存地址中。没有关系(与引用类型不同)。或者换一种说法bools[0] != SomeClass.boolA。更改bools[0] 不会影响SomeClass.boolA,反之亦然。

你可以通过运行这段代码看到这一点:

bool a = false;
bool[] bools = new bool[] {a};
bools[0] = true;

a == false; //true
bools[0] == true; //true

所以你不能做你想做的事。基本上你将不得不独立操作SomeClass.boolA等,可能使用switchif

【讨论】:

  • 如果我们要存储引用类型,您尝试执行的操作会起作用,仅供参考,但它不适用于值类型。
猜你喜欢
  • 1970-01-01
  • 2016-07-20
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 2018-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多