繁体   English   中英

运算符“==”不能应用于“char”和“string”类型的操作数

[英]Operator ‘==’ cannot be applied to operands of type ‘char’ and ‘string’

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

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

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

运算符“==”不能应用于“char”和“string”类型的操作数

    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)");
        }
    }

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

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

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

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

        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]);

因为您没有将返回值分配给变量,所以 plus 'cl' 已经包含该特定值的小写。

这条线

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

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

应用时 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# 似乎肯定将单个字符周围的单引号视为 Char,而不是字符串。

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

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

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

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

在此处输入图片说明

尝试使用此比较:

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

当数组具有 .Contains 方法时,循环遍历数组只是为了查看其中是否包含元素是一种矫枉过正。 没有 for 循环的类似这样的事情应该可以工作:

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

if(char[0].ToString() == "!") print("do something");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM