简体   繁体   English

是否存在检查字符串是否为空的边缘情况?

[英]Are there edge cases for checking if a string is null?

I recently took ownership of some code from an author that is no longer with the company. 我最近获得了一位不再与该公司合作的作者的一些代码。 Throughout the code I'm finding this line 在整个代码中,我找到了这一行

if (string.Compare(string.Empty, textbox1.Text, true) == 0)

I'm not the most advanced C# programmer, but to me that seems functionally the same as 我不是最先进的C#程序员,但对我来说,功能上看起来和我一样

if (textbox1.Text == "")

Is there any edge case that the first line will catch that the second one won't? 是否有任何边缘情况,第一行将捕获第二行不会?

Actually, you should use String.IsNullOrEmpty(textbox1.Text) instead. 实际上,您应该使用String.IsNullOrEmpty(textbox1.Text)

As pointed out in the comments, String.IsNullOrWhitespace is especially useful since you're working with GUI controls, which often may contain just whitespace, and not actually be an "empty" string. 正如评论中所指出的, String.IsNullOrWhitespace特别有用,因为你正在使用GUI控件,它通常只包含空格,而实际上并不是一个“空”字符串。

It is comparing string ignoring case , but its a bad way of doing it. 它是比较字符串忽略的情况 ,但它是一种不好的方式。 String.Equals has an overload for comparing strings with ignoring case. String.Equals有一个重载,用于比较字符串和忽略大小写。

To check if string consist of empty string, String.IsNullOrEmpty should be used, if you are using .Net framework 4.0 or higher and you want to consider space as empty string then you can use string.IsNullOrWhiteSpace . 要检查字符串是否由空字符串组成,应使用String.IsNullOrEmpty ,如果使用.Net framework 4.0或更高版本,并且要将空间视为空字符串,则可以使用string.IsNullOrWhiteSpace

If you only want to compare the value with empty string then textbox1.Text == "" or textbox1.Text == string.Empty is enough. 如果您只想将值与空字符串进行比较,则textbox1.Text == ""textbox1.Text == string.Empty就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM