簡體   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