【问题标题】:Operator ‘==’ cannot be applied to operands of type ‘char’ and ‘string’运算符“==”不能应用于“char”和“string”类型的操作数
【发布时间】:2013-10-12 20:40:54
【问题描述】:

我正在开发一个自我指导的简单程序来练习我迄今为止学到的概念。我的项目与国际象棋有关,在这种情况下特别是棋盘(a-h 列和 1-8 行)。要求用户输入特定棋子的当前位置,希望将其输入为列的字母,后跟行的数字。 为了验证这一点,我首先检查这个值是否输入为两个字符的字符串,否则输入的内容已经不正确。 然后,我将输入的字符串转换为小写字符,然后将其与可接受的数组元素列表进行比较。

通过搜索此site,我得到的印象是字符串将其字符存储为数组,并使用字符串的char 属性,您将能够提取第一个字符,从而将char 与char 进行比较。在我的搜索中,我还没有找到任何足够具体的东西来真正让我对正在发生的事情有一个很好的了解。 This 是我遇到的最接近的选项,但我觉得不适用于这种情况。任何见解将不胜感激。

下面的代码会产生以下错误。

运算符“==”不能应用于“char”类型的操作数和 ‘字符串’

    private char[] gridColumns = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', };

    private void createMoveButton_Click(object sender, RoutedEventArgs e)
    {
        // Assigns text box input to associated private fields
        this.gameId = this.gameIdTextBox.Text;
        this.playerId = this.playerIdTextBox.Text;
        this.gamePiece = this.gamePieceTextBox.Text;
        this.currentLocation = this.currentLocationTextBox.Text;
        this.targetLocation = this.targetLocationTextBox.Text;

        // Current location should only ever be 2 characters, ensure from the start this is true.
        if (currentLocationTextBox.Text.Length == 2)
        {
            // Converts contents of currentLocationTextBox to lower case characters for comparison.
            string cl = currentLocation.ToLowerInvariant();

            // Iterates through my array of possible column choices
            for (int i = 0; i < gridColumns.Length; i++)
            {
                Char.ToLowerInvariant(currentLocationTextBox.Text[0]);
                // Trying to compare the first character of my string to the char element of my array.
                if (cl[0] == gridColumns[i])
                {
                    //TODO
                }
            }
        }
        else
        {
            MessageBox.Show("Check your starting location. It needs to be a lower case character variable (a-h) followed by a number (1-8)");
        }
    }

【问题讨论】:

  • 我在你的代码中看到了string gamePiece,但我没有看到数组gamePieces。您是否将两者混淆了,或者它真的是其他地方的单独数组?

标签: c# .net arrays string char


【解决方案1】:

与 C 不同,字符串和 char 数组是不同的。 C# 中的字符串可以视为 char 数组,但您应该认为它们不同,因此 '==' 比较不合适。一种简单的查看方法是使用以下简单表达式

   if ("a" == 'a') { /* do something */ } // ERROR!

看起来它应该可以工作,但它会产生与您看到的相同的错误,因为它试图将字符串“a”与字符“a”进行比较。在您的示例代码中,文本框控件的 Text 属性是字符串类型。

字符串类有一个索引器,允许您将字符串视为 char 数组,但通常最好(更简单)使用众多字符串方法之一来实现您的目标。考虑一下:

        var gridcolumns = "abcdefgh";
        var gridrows = "12345678";
        var input = "a1"; // column row
        var col = gridcolumns.IndexOf(input[0]); // 0 -7
        var row = gridrows.IndexOf(input[1]); // 0 -7

在您提供的代码中,我没有看到会产生您提供的错误的行。以下行没有任何用处

           Char.ToLowerInvariant(currentLocationTextBox.Text[0]);

因为您没有将返回的值分配给变量,加上“cl”已经包含该特定值的小写。

这一行

            if (cl[0] == gridColumns[i])

不应产生错误,因为这两个项目都是 char 类型。

【讨论】:

  • 感谢您的解释和建议。我知道这里有很多人只是在寻找快速的答案,但有时只是让某人向你解释一些东西而不是试图从阅读中理解这个概念是有帮助的。谢谢。
【解决方案2】:

应用时 Dweeberly 的回答......并缩短: 答:把单引号改成双引号。

我的理由: 假设如下代码:

string IAmAString;
// set string to anything
IAmAString = "Q";
if (IAmAString == 'Q')
{
 // do something, but never gets here because "Q" is a string, and 'Q' is a char
 // Intellisense gives error on the if statement of 
 // 
 // "Operator '==' cannot be applied to operands of types 'string' and 'char'"
 //
 // because C# is a strongly typed language, and the '==' is not by 
 // default (in VS2012) overloaded to compare these two different types.
 // You are trying to compare a string with something that
 // is not-string, and C# is trying to let you know 
 // that that is not going to work.
}

通过将引号更改为双引号来解决此问题。 C# 似乎将单个字符周围的单引号视为字符,而不是字符串。

只需更改 if 语句中的引号:

IAmAString = "Q";
if (IAmAString == "Q")
{
 // does whatever is here within reason; "Q" is a string and "Q" is a string
}

至少这对我有用,这就是我对原因的“快速”(其中“q”!=“q”)解释。
回去工作...

【讨论】:

    【解决方案3】:

    尝试使用这种比较:

    (cl.ToCharArray())[0] == gridColumns[i]
    

    【讨论】:

    • 实际上cl[0] 工作得更好,因为它的代码更少,而且不需要将整个字符串复制到一个新数组中。
    【解决方案4】:

    我运行了你的程序,它运行良好。我认为问题出在其他地方。

    【讨论】:

    • 我假设这会将两者都转换为字符串以进行比较,但是通过使用 [0] 选择字符串的第一个字符,您只是在比较 char 和 char 时不做同样的事情吗?我想这是我在理解方面遇到困难的部分。
    • @TargetofGravity: 你的变量是gamePieces 还是gamePiece?阅读 music_coder 的评论。
    • 抱歉,我在反复试验中没有完全重构。实际变量应该是 gridColumns 来引用有问题的数组,谢谢。
    • @TargetofGravity:那么你仍然遇到同样的编译器错误吗?
    • 实际上没有。我无法解释它,但关闭并重新打开 VS 清除它。在此之前,我曾尝试过没有运气的重建以及干净的解决方案和重建。我想我不确定发生了什么。我不确定是否有其他人经历过这种情况,但有时在 VS 中,由于缺少更好的术语,一些捷径会显得“有趣”。例如,当您剪切并粘贴某些内容时,它并不总是重新粘贴您剪切的内容,撤消将同样零星地删除内容。到目前为止,这个问题的重启也是我目前的修复。
    【解决方案5】:

    当一个数组有一个 .Contains 方法时,循环遍历数组只是为了查看一个元素是否包含在其中。像这样没有 for 循环的东西应该可以工作:

        if (gridColumns.Contains(cl[0]))
        {
            //TODO
        } 
    

    【讨论】:

    • 我很欣赏这个建议,但不知道。
    • 这个Contains实际上不在阵列上;它是来自System.Linq.Enumerable 的 Linq 扩展。
    【解决方案6】:

    if(char[0].ToString() == "!") print("做某事");

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      • 2019-02-13
      相关资源
      最近更新 更多