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

标签 c#

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

if (state != 'WI' && state != 'IL')

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

如果这是不可能的,有什么方法可以实现我的目标。

最佳答案

对字符串使用双引号:

if (state != "WI" && state != "IL")

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

char c = 'A';
if (c != 'B') ...

编辑:其他人建议使用 Equals 进行比较,我不完全同意它应该取代 == 方法,除非你有理由使用它。首先,如果 statenull,则写入 state.Equals("WI") 时将抛出异常。解决此问题的一种方法是改用 String.Compare(state, "WI") 但它不再返回 bool 并且需要对照整数 (0如果它们相同则返回):

if (String.Compare(state, "WI") != 0)

其次,如果区分大小写很重要,我建议使用 EqualsString.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/

相关文章:

c# - 将异步操作结果返回给原线程

c# - 从子类递增数组

c#如何让用户名出现在另一个网页上

c# - .Net 多个客户端和中央服务器之间的数据同步

c# - C# 中具有未定义行为的代码

C#7 : Underscore ( _ ) & Star ( * ) in Out variable

c# - Caliburn Micro,如何首先使用 ViewModel 使用 ContentControl(或显示 'sub' ViewModel)

c# - 在没有递归的情况下匹配递归模式

c# - 将 CancellationToken 传递给任务类构造函数有什么用?

c# - PictureBox PaintEvent 与其他方法