尝试将值与字符串进行比较时C#出错

Jos*_* U. 1 c#

在C#中尝试以下操作时出现错误

if (state != 'WI' && state != 'IL')
Run Code Online (Sandbox Code Playgroud)

该语句给出了一个错误,指出:Error operator!=不能应用于'string'或'char'类型的操作数

如果这不可能,那么什么是实现我的目标的方法.

Ahm*_*eed 6

对字符串使用双引号:

if (state != "WI" && state != "IL")
Run Code Online (Sandbox Code Playgroud)

单引号对单个字符很有用:

char c = 'A';
if (c != 'B') ...
Run Code Online (Sandbox Code Playgroud)

编辑:其他人建议使用Equals比较,我不完全同意它应该取代一种==方法,除非你有理由使用它.首先,如果 state是,null那么将从写作中抛出异常state.Equals("WI").解决这个问题的方法是使用String.Compare(state, "WI")而不是返回a bool并且需要针对整数进行检查(如果它们相同则返回0):

if (String.Compare(state, "WI") != 0)
Run Code Online (Sandbox Code Playgroud)

其次,我建议使用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
Run Code Online (Sandbox Code Playgroud)