C# 默认字符串初始化:NULL 还是 Empty?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/265875/
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
Default string initialization: NULL or Empty?
提问by vfilby
I have always initialized my strings to NULL, with the thinking that NULL means the absence of a value and "" or String.Empty is a valid value. I have seen more examples lately of code where String.Empty is considered the default value or represents no value. This strikes me as odd, with the newly added nullable types in c# it seems like we are taking strides backwards with strings by not using the NULL to represent 'No Value'.
我总是将我的字符串初始化为 NULL,认为 NULL 意味着没有值,而 "" 或 String.Empty 是有效值。我最近看到了更多代码示例,其中 String.Empty 被视为默认值或不代表任何值。这让我觉得很奇怪,在 c# 中新添加的可空类型似乎我们正在通过不使用 NULL 来表示“无值”的字符串向后迈进。
What do you use as the default initializer and why?
您使用什么作为默认初始化程序,为什么?
Edit: Based on the answers I futher my further thoughts
编辑:根据答案,我进一步思考
Avoiding error handlingIf the value shouldn't be null, why did it get set to
NULL
in the first place? Perhaps it would be better to identify the error at the place where it occurs rather than cover it up through out the rest of your codebase?Avoiding null checksIf you are tired of doing null checks in code, wouldn't it be better to abstract the null checks? Perhaps wrap (or extend!) the string methods to make them
NULL
safe? What happens if you constantly useString.Empty
and a null happens to work it's way into your system, do you start addingNULL
checks anyways?
避免错误处理如果该值不应该为空,为什么
NULL
首先将其设置为?也许最好在错误发生的地方识别错误,而不是在代码库的其余部分掩盖它?避免空检查如果您厌倦了在代码中进行空检查,那么抽象空检查不是更好吗?也许包装(或扩展!)字符串方法以使它们
NULL
安全?如果您经常使用String.Empty
并且 null 恰好在您的系统中工作会发生什么,您是否开始添加NULL
检查?
I can't help but return to the opinion that it is laziness. Any DBA would slap you nine ways to silly if you used '' instead of null
in his\her database. I think the same principles apply in programming and there should be somebody to smack those upside the head who use String.Empty
rather than NULL
to represent no value.
我不禁回到了懒惰的观点。如果您使用 '' 而不是null
在他/她的数据库中,那么任何 DBA 都会用九种方式来愚蠢地打您。我认为同样的原则适用于编程,应该有人抨击那些使用String.Empty
而不是NULL
代表没有价值的人。
Related Questions
相关问题
采纳答案by Adam Liss
+1 for distinguishing between "empty" and NULL. I agree that "empty" should mean "valid, but blank" and "NULL" should mean "invalid."
+1 用于区分“空”和 NULL。我同意“空”应表示“有效,但为空白”,“NULL”应表示“无效”。
So I'd answer your question like this:
所以我会这样回答你的问题:
emptywhen I want a valid default value that may or may not be changed, for example, a user's middle name.
当我想要一个可能会或可能不会更改的有效默认值时为空,例如,用户的中间名。
NULLwhen it is an error if the ensuing code does not set the value explicitly.
如果后续代码未明确设置该值,则为NULL。
回答by Dana the Sane
Is it possible that this is an error avoidance technique (advisable or not..)? Since "" is still a string, you would be able to call string functions on it that would result in an exception if it was NULL?
这是否可能是一种错误避免技术(可取与否..)?由于 "" 仍然是一个字符串,您将能够在其上调用字符串函数,如果它是 NULL,则会导致异常?
回答by Rob Prouse
It depends on the situation. In most cases I use String.Empty because I don't want to be doing null checks every time I attempt to use a string. It makes the code a lot simpler and you are less likely to introduce unwanted NullReferenceException crashes.
这取决于实际情况。在大多数情况下,我使用 String.Empty 因为我不想每次尝试使用字符串时都进行空检查。它使代码更简单,并且不太可能引入不需要的 NullReferenceException 崩溃。
I only set the string to null when I need to know if it has been set or not and where an empty string is something valid to set it to. In practice, I find these situations rare.
我只在需要知道它是否已设置以及空字符串是否可以设置为有效时才将字符串设置为 null。在实践中,我发现这些情况很少见。
回答by Surgical Coder
I either set it to "" or null - I always check by using String.IsNullOrEmpty, so either is fine.
我要么将其设置为 "" 或 null - 我总是使用 String.IsNullOrEmpty 进行检查,所以两者都可以。
But the inner geek in me says I should set it to null before I have a proper value for it...
但是我内心的极客说我应该在我有一个合适的值之前将它设置为空......
回答by Tomalak
回答by Herms
It depends.
这取决于。
Do you need to be able to tell if the value is missing (is it possible for it to not be defined)?
您是否需要能够判断该值是否缺失(是否有可能无法定义)?
Is the empty string a valid value for the usage of that string?
空字符串是否是使用该字符串的有效值?
If you answered "yes" to both, then you'll want to use null. Otherwise you can't tell the difference between "no value" and "empty string".
如果您对两者都回答“是”,那么您将要使用 null。否则你无法分辨“无值”和“空字符串”之间的区别。
If you don't need to know if there's no value then the empty string is probably safer, as it allows you to skip null checks wherever you use it.
如果您不需要知道是否没有值,那么空字符串可能更安全,因为它允许您在任何使用它的地方跳过空检查。
回答by Greg Smalter
This is actually a gaping hole in the C# language. There is no way to define a string that cannot be null. This causes problems as simple as the one you are describing, which forces programmers to make a decision they shouldn't have to make, since in many cases NULL and String.Empty mean the same thing. That, in turn, can later force other programmers to have to handle both NULL and String.Empty, which is annoying.
这实际上是 C# 语言中的一个大漏洞。无法定义不能为空的字符串。这会导致与您所描述的问题一样简单的问题,这迫使程序员做出他们不应该做出的决定,因为在许多情况下 NULL 和 String.Empty 意味着相同的事情。这反过来又会迫使其他程序员必须同时处理 NULL 和 String.Empty,这很烦人。
A bigger problem is that databases allow you to define fields that map to a C# string, but database fields can be defined as NOT NULL. So, there is no way to accurately represent, say, a varchar( 100 ) NOT NULL field in SQL Server using a C# type.
更大的问题是数据库允许您定义映射到 C# 字符串的字段,但数据库字段可以定义为 NOT NULL。因此,无法使用 C# 类型准确表示 SQL Server 中的 varchar(100) NOT NULL 字段。
Other languages, such as Spec #, do allow this.
其他语言,例如 Spec #,确实允许这样做。
In my opinion, C#'s inability to define a string that doesn't allow null is just as bad as its previous inability to define an int that does allow null.
在我看来,C# 无法定义不允许为 null 的字符串与之前无法定义允许为 null 的 int 一样糟糕。
To completely answer your question: I always use empty string for default initialization because it is more similar to how database data types work. (Edit: This statement was very unclear. It should read "I use empty string for default initialization when NULL is a superfluous state, much in the same way I set up a database column as NOT NULL if NULL would be a superfluous state. Similarly, many of my DB columns are set up as NOT NULL, so when I bring those into a C# string, the string will be empty or have a value, but will never be NULL. In other words, I only initialize a string to NULL if null has a meaning that is distinct from the meaning of String.Empty, and I find that case to be less than common (but people here have given legitimate examples of this case).")
完全回答您的问题:我总是使用空字符串进行默认初始化,因为它更类似于数据库数据类型的工作方式。(编辑:此语句非常不清楚。它应该显示为“当 NULL 是多余状态时,我使用空字符串进行默认初始化,这与我将数据库列设置为 NOT NULL 如果 NULL 是多余状态的方式非常相似。类似地, 我的很多 DB 列都设置为 NOT NULL,所以当我将它们带入 C# 字符串时,该字符串将为空或有值,但永远不会为 NULL。换句话说,我只将字符串初始化为 NULL如果 null 的含义与 String.Empty 的含义不同,我发现这种情况不太常见(但这里的人们已经给出了这种情况的合理示例)。”)
回答by yfeldblum
An empty string is a value (a piece of text which, incidentally, happens not to contain any letters). Null signifies no-value.
空字符串是一个值(一段文本,顺便说一下,不包含任何字母)。Null 表示无值。
I initialize variables to null when I wish to indicate that they do not point to or contain actual values - when the intent is for no-value.
当我希望表明它们不指向或不包含实际值时,我将变量初始化为 null - 当意图是无值时。
回答by Robert Rossney
For most software that isn't actually string-processing software, program logic ought not to depend on the content of string variables. Whenever I see something like this in a program:
对于实际上不是字符串处理软件的大多数软件,程序逻辑不应该依赖于字符串变量的内容。每当我在程序中看到这样的事情时:
if (s == "value")
I get a bad feeling. Why is there a string literal in this method? What's setting s
? Does it know that logic depends on the value of the string? Does it know that it has to be lower case to work? Should I be fixing this by changing it to use String.Compare
? Should I be creating an Enum
and parsing into it?
我有一种不好的感觉。为什么在这个方法中有一个字符串文字?什么设置s
?它知道逻辑取决于字符串的值吗?它知道它必须是小写才能工作吗?我应该通过将其更改为使用来解决此问题String.Compare
吗?我应该创建一个Enum
并解析它吗?
From this perspective, one gets to a philosophy of code that's pretty simple: you avoid examining a string's contents wherever possible. Comparing a string to String.Empty
is really just a special case of comparing it to a literal: it's something to avoid doing unless you really have to.
从这个角度来看,我们得到了一种非常简单的代码哲学:尽可能避免检查字符串的内容。将字符串与字符串进行String.Empty
比较实际上只是将其与文字进行比较的一种特殊情况:除非您确实必须这样做,否则应避免这样做。
Knowing this, I don't blink when I see something like this in our code base:
知道这一点,当我在我们的代码库中看到这样的东西时,我不会眨眼:
string msg = Validate(item);
if (msg != null)
{
DisplayErrorMessage(msg);
return;
}
I know that Validate
would never return String.Empty
, because we write better code than that.
我知道那Validate
永远不会返回String.Empty
,因为我们编写的代码比那更好。
Of course, the rest of the world doesn't work like this. When your program is dealing with user input, databases, files, and so on, you have to account for other philosophies. There, it's the job of your code to impose order on chaos. Part of that order is knowing when an empty string should mean String.Empty
and when it should mean null
.
当然,世界其他地方不是这样运作的。当您的程序处理用户输入、数据库、文件等时,您必须考虑其他理念。在那里,您的代码的工作是在混乱中强加秩序。该顺序的一部分是知道空字符串何时应表示String.Empty
以及何时应表示为null
。
(Just to make sure I wasn't talking out of my ass, I just searched our codebase for `String.IsNullOrEmpty'. All 54 occurrences of it are in methods that process user input, return values from Python scripts, examine values retrieved from external APIs, etc.)
(为了确保我不是胡说八道,我只是在我们的代码库中搜索了 `String.IsNullOrEmpty'。所有 54 次出现在处理用户输入的方法中,从 Python 脚本返回值,检查从外部 API 等)
回答by Tor Haugen
Strings aren't value types, and never will be ;-)
字符串不是值类型,永远不会是 ;-)