在 C# 中编写 null 或empty 的更简单方法?
我确信我在这里错过了一些东西。对于某个项目,我需要检查字符串是否为空或空。
有没有更简单的方法来写这个?
if (myString == null || myString == "")
{
...
I'm sure I've missed something here. With a certain project I need to check if a string is null or empty.
Is there an easier way of writing this?
if (myString == null || myString == "")
{
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
是的,有
String.IsNullOrEmpty
< /a> 辅助方法已经实现了这一点:Yes, there's the
String.IsNullOrEmpty
helper method for exactly this already:或者您可以利用扩展方法中的一个怪癖,它们允许 this 为 null:
然后让您编写:
尽管您可能应该选择“空”之外的其他名称。
Or you could take advantage of a quirk in extension methods, they allow this to be null:
which then lets you write:
Although you probably should pick another name than 'empty'.
如果您使用的是 .NET 4,则可以使用
else:
If you are on .NET 4, you can use
else:
为了避免空检查,您可以使用 ??操作员。
我经常使用它作为警卫,以避免在方法中发送我不需要的数据。
它还可用于避免不必要的格式化。
这也可以用在 if 语句中,虽然不太好,但有时很方便。
To avoid null checks you can use ?? operator.
I often use it as guards to avoid sending in data that I don't want in methods.
It can also be used to avoid unwanted formatting.
This can also be used in if statements, it's not so nice but can be handy sometimes.
在 c# 9 中,通过使用模式匹配,您可以执行以下操作
In c# 9 by using pattern matching you could do the following
C# 9 的模式匹配允许您编写:
C# 9's pattern matching allows you to write:
// 如果字符串未定义为 null,则 IsNullOrEmpty 效果很好,但如果字符串定义为 null,则修剪将抛出异常。
//您可以使用 IsNullOrWhiteSpace ,它对于字符串中的多个空格效果很好。即它对于多个空格也返回 true
// if the string is not defined to null then IsNullOrEmpty it works great but if string is defined null then trim will throw exception.
//you can use IsNullOrWhiteSpace which work well for multiple white space in string .i.e it return true for multiple white space also