在 C# 中检查 null 和 string.Empty

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/471663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 04:42:54  来源:igfitidea点击:

Checking null and string.Empty in C#

c#.net

提问by Ash

This might sound like a noob question, but are:

这听起来像是一个菜鸟问题,但实际上是:

string var;
if (var == null)

and

string var;
if (var == string.Empty)

The same?

相同?

Duplicate

What's the Difference between String.Empty and Null?and In C#, should I use String.Empty or Null?

复制

String.Empty 和 Null 有什么区别?在C#中,我应该使用的String.Empty或空?

采纳答案by Kevin Tighe

@Jay is correct, they are not the same. String.IsNullOrEmpty()is a convenient method to check for both null and "".

@Jay 是对的,它们不一样。 String.IsNullOrEmpty()是检查 null 和 "" 的便捷方法。

回答by Jay Bazuzi

No, they are not the same.

不,它们不一样。

string.Emptyis the same as "", which is an actual object: a string of 0 length. nullmeans there is no object.

string.Empty与 相同"",它是一个实际对象:长度为 0 的字符串。 null表示没有对象。

回答by Ilya Volodin

No, they are not. First one checks if the variable has been initialized or if it was set to "null" later. Second one checks if the value of the variable is "" (empty). However, you shouldn't use either. You should use string.IsNullOrEmpty(var) instead.

不,他们不是。第一个检查变量是否已初始化或稍后是否设置为“null”。第二个检查变量的值是否为“”(空)。但是,您也不应该使用它们。您应该使用 string.IsNullOrEmpty(var) 代替。

回答by Antonio Pelleriti

they are not the same, the implementation of String.IsNullOrEmpty(string) in mscorlib demonstrate it:

它们不一样,mscorlib 中 String.IsNullOrEmpty(string) 的实现演示了它:

public static bool IsNullOrEmpty(string value)
{
    if (value != null)
    {
        return (value.Length == 0);
    }
    return true;
}

回答by wiener

But sometimes you want to know if the string is NULLand it does not matter that its empty (in a OO design). For example you have a method and it will return NULLor a string.you do this because null means the operation failed and an empty string means there is no result.

但有时您想知道字符串是否是NULL空的(在 OO 设计中)并不重要。例如,您有一个方法,它会返回NULLstring.您这样做,因为 null 表示操作失败,空字符串表示没有结果。

In some cases you want to know if it failed or if it has no result prior to take any further actions in other objects.

在某些情况下,在对其他对象采取任何进一步操作之前,您想知道它是否失败或是否没有结果。