加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 运算符’==’不能应用于’char’和’string’类型的操作数

发布时间:2020-12-16 01:57:37 所属栏目:百科 来源:网络整理
导读:我正在研究一个自我导向的简单程序来练习到目前为止我学到的概念.我的项目与国际象棋有关,在这种情况下特别是棋盘(a-h栏和1-8栏).用户被要求输入特定棋子的当前位置,该棋子希望作为该列的字母输入,后跟该行的数字. 为了验证这一点,我首先要检查这个值是否输
我正在研究一个自我导向的简单程序来练习到目前为止我学到的概念.我的项目与国际象棋有关,在这种情况下特别是棋盘(a-h栏和1-8栏).用户被要求输入特定棋子的当前位置,该棋子希望作为该列的字母输入,后跟该行的数字.
为了验证这一点,我首先要检查这个值是否输入为两个字符的字符串,否则输入的内容已经不正确.
然后我将输入的字符串转换为小写字符,然后将其与可接受的数组元素列表进行比较.

从搜索这个site我得到的印象是一个字符串将其字符存储为一个数组,并使用字符串的char属性,您将能够拉出第一个字符,从而将char与char进行比较.我还没有在搜索中发现任何具体的内容,以便让我对发生的事情有一个很好的理解. This是我遇到的最接近的选项,我觉得不适用于这种情况.任何见解将不胜感激.

后面的代码会产生以下错误.

Operator ‘==’ cannot be applied to operands of type ‘char’ and
‘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不同,字符串和char数组是不同的. C#中的字符串可以被视为char数组,但您应该将它们视为不同,因此’==’比较是不合适的.一个简单的方法是使用以下简单表达式

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

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

字符串类有一个索引器,允许您将字符串视为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类型.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读