在 C# 中尝试以下操作时出现错误
if (state != 'WI' && state != 'IL')
该语句给我一个错误,指出:错误运算符 != 不能应用于 'string' 或 'char' 类型的操作数
如果这是不可能的,有什么方法可以实现我的目标。
最佳答案
对字符串使用双引号:
if (state != "WI" && state != "IL")
单引号对单个字符很有用:
char c = 'A';
if (c != 'B') ...
编辑:其他人建议使用 Equals
进行比较,我不完全同意它应该取代 ==
方法,除非你有理由使用它。首先,如果 state
为 null
,则写入 state.Equals("WI")
时将抛出异常。解决此问题的一种方法是改用 String.Compare(state, "WI")
但它不再返回 bool
并且需要对照整数 (0如果它们相同则返回):
if (String.Compare(state, "WI") != 0)
其次,如果区分大小写很重要,我建议使用 Equals
或 String.Compare
,因为两者都提供重载来处理该问题:
string foo = "Foo";
string otherFoo = "foo";
Console.WriteLine("Equals: {0}", foo.Equals(otherFoo));
Console.WriteLine("Equals case insensitive: {0}", foo.Equals(otherFoo, StringComparison.InvariantCultureIgnoreCase));
Console.WriteLine("Compare: {0}", String.Compare(foo, otherFoo) == 0);
Console.WriteLine("Compare case insensitive: {0}", String.Compare(foo, otherFoo, StringComparison.InvariantCultureIgnoreCase) == 0);
// make foo null
foo = null;
Console.WriteLine("Null Compare: {0}", String.Compare(foo, otherFoo) == 0);
Console.WriteLine("Null Equals: {0}", foo.Equals(otherFoo)); // exception
关于c# - 尝试将值与字符串进行比较时 C# 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4059809/