简体   繁体   English

处理空/空字符串

[英]Handling null / empty string

Before .NET 4 is out, we've been doing something like this to check for null / empty string : 在.NET 4发布之前,我们一直在做这样的事情来检查null / empty字符串:

String s;
if ((s + "").Trim().Length == 0)
{
    //do something
}

While the above method works pretty well for us, I know that in .NET 4, we got a IsNullOrWhiteSpace method to do the similar thing. 虽然上面的方法对我们来说很好用,但是我知道在.NET 4中,我们有一个IsNullOrWhiteSpace方法来做类似的事情。

My question is, which one is better? 我的问题是,哪个更好? Do we should switch to use the built-in function instead? 我们是否应该改用内置功能?

On .NET 4, I'd definitely use the built in method. 在.NET 4上,我肯定会使用内置方法。 After all, it says exactly what you're trying to do. 毕竟,它恰好说明了您要做什么。

If you're stuck before .NET 4, why not use: 如果您陷于.NET 4之前,为什么不使用:

if (s == null || s.Trim() == "")

Or 要么

if (s == null || s.Trim().Length == 0)

? Both of those say what you want to achieve. 这两个人都说您想要实现的目标。

I definitely wouldn't use string concatenation here. 我绝对不会在这里使用字符串连接。 Performance aside, you're not interested in string concatenation. 除了性能之外,您对字符串连接不感兴趣。 Whenever you find your code doing something which really isn't part of what you're trying to achieve, you should try to improve it for the sake of readability. 每当发现您的代码所做的事情确实不属于您要实现的工作时,就应该为了可读性而尝试对其进行改进。

I personally use IsNullOrWhiteSpace , mostly because using it makes code clearer to read and it handles more cases (the WhiteSpace part). 我个人使用IsNullOrWhiteSpace ,主要是因为使用IsNullOrWhiteSpace可以使代码阅读起来更清晰,并且可以处理更多情况( WhiteSpace部分)。 It depends on your preferences, because both methods does pretty the same thing. 这取决于您的首选项,因为这两种方法都做同样的事情。

Why not write a helper method to implement what IsNullOrWhiteSpace does before .NET 4? 为什么不编写一个辅助方法来实现.NET 4之前IsNullOrWhiteSpace功能呢? Just like 就像

public static boolean IsNullOrWhiteSpace(string input)
{
    return string.IsNullOrEmpty(input) || input.Trim() == string.Empty;
}

Don't use concatenation here as Jon said. 请勿像乔恩所说的那样使用串联。 It's not a good practice for checking null/empty. 检查null / empty不是一个好习惯。

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

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