将字符串拼接在一起,与操作员'=='

时间:2018-03-06 13:42:38

标签: c#

我有8个按钮,几乎都做同样的事情,将0更改为按1&的按钮Dout0_Click DoutState0我想这样做,没有复制并粘贴相同的代码8次......

    int DoutState0 = 0; // 0(off) or 1(on)

    private void Dout0_Click(object sender, EventArgs e)
    {
        if (DoutState0 == 0)
        {
            DoutState0 = 1;
        }
        else
        {
            DoutState0 = 0;
        }
    }

所以我想到了这段代码

    int DoutNumber = 0; // 0,1,2,3,4,5,6,7 

    int DoutState0 = 0; // 0(off) or 1(on)
    int DoutState1 = 0;
    int DoutState2 = 0;
    int DoutState3 = 0;
    int DoutState4 = 0;
    int DoutState5 = 0;
    int DoutState6 = 0;
    int DoutState7 = 0;

    public void TogleDOUT()
    {
        string CheckDout = $"DoutState{DoutNumber}";
        Console.WriteLine(CheckDout);  // prints 'DoutState0' and not '0' as expected 

        if (CheckDout == 0)
        {
            //update CheckDout from '0' to '1'
        }
        else
        {
            //update CheckDout from '1' to '0'
        }

    }


    private void Dout0_Click(object sender, EventArgs e)
    {
        DoutNumber = 0;
        TogleDOUT();
    }

但是收到此错误Operator '==' cannot be applied to operands of type 'string' and 'int'

我不确定我在这里做错了什么......

1 个答案:

答案 0 :(得分:-3)

如果您有DoutNumber == 0,则您的0需要使用"0"之类的引号,因为它将int与字符串进行比较