我正在开发一个自我指导的简单程序来练习迄今为止学到的概念。我的项目与国际象棋相关,在本例中具体是棋盘(a-h 列和 1-8 行)。系统会询问用户特定棋子的当前位置,希望输入为列字母,后跟行数字。
为了验证这一点,我首先检查该值是否作为两个字符的字符串输入,否则输入的内容已经不正确。
然后,我将输入的字符串转换为小写字符,然后将其与可接受的数组元素列表进行比较。
从搜索这个site https://stackoverflow.com/questions/7922890/in-c-parse-string-into-individual-characters我的印象是字符串将其字符存储为数组并使用char http://msdn.microsoft.com/en-us/library/system.string.chars.aspx字符串的属性,您将能够拉出第一个字符,从而将字符与字符进行比较。在我的搜索中,我还没有找到任何足够具体的东西来真正让我很好地了解正在发生的事情。This https://stackoverflow.com/questions/19033642/operator-cannot-be-applied-to-operands-of-type-char-and-string是我遇到的最接近的选项,我认为它不适用于这种情况。任何见解将不胜感激。
下面的代码会产生以下错误。
运算符“==”不能应用于“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)");
}
}
与 C 不同,字符串和字符数组是不同的。 C# 中的字符串可以被视为 char 数组,但您应该考虑它们不同,因此 '==' 比较是不合适的。查看这一点的一种简单方法是使用以下简单表达式
if ("a" == 'a') { /* do something */ } // ERROR!
看起来它应该可以工作,但它会生成与您所看到的相同的错误,因为它试图将字符串“a”与字符“a”进行比较。在您的示例代码中,文本框控件的 Text 属性是字符串类型。
字符串类有一个索引器,允许您将字符串视为字符数组,但通常使用众多字符串方法之一来实现您的目标更好(更简单)。考虑一下:
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 类型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)