C# 如何将字符串的值设置为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11193906/
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-09 16:56:47  来源:igfitidea点击:

How to set the value of string to null

c#c#-4.0

提问by Ajax3.14

I am aware that I can set null like

我知道我可以像这样设置 null

string val = null;

But I am wondering the other ways I can set it to null. Is there a funcion like String.nullthat I can use.

但我想知道我可以将它设置为空的其他方法。有没有String.null我可以使用的功能。

采纳答案by Asif Mushtaq

I think you are looking far String.Empty

我想你看得很远 String.Empty

string val = String.Empty;

Update:TheFuzzyGigglercomments are worth mentioning:

更新:TheFuzzyGiggler评论值得一提:

It's much better to set a stringto emptyrather than null. To avoid exceptions later. If you have to read and write a lot of strings you'll have nullvalue exceptions all over the place. Or you'll have a ton of if(!string.isNullorEmpty(string))which get annoying

设置一个stringtoempty而不是null. 以免以后出现异常。如果您必须读取和写入大量字符串,您将null到处都有值异常。否则你会有很多if(!string.isNullorEmpty(string))烦人的

回答by Wormbo

nullis not a special string value (there's String.Emptyfor ""), but a general object literal for the empty reference.

null不是特殊的字符串值(有String.Emptyfor ""),而是空引用的通用对象字面量。

回答by Seth Flowers

You can also use the default keyword.

您也可以使用 default 关键字。

string val = default(string);

Here is another SO question regarding the default keyword: What is the use of `default` keyword in C#?

这是关于 default 关键字的另一个 SO 问题: What is the use of `default` keyword in C#?

回答by Joel B

Depending on your application you could use string.Empty. I'm always leery of initializing to nullas the garbage collector is great, but not perfect, and could mark your string for garbage collection if used in some way that the garbage collector can't detect (this is very unlikely though).

根据您的应用程序,您可以使用string.Empty. 我总是对初始化持怀疑态度,null因为垃圾收集器很棒,但并不完美,如果以垃圾收集器无法检测到的某种方式使用,可以将您的字符串标记为垃圾收集(尽管这不太可能)。

回答by Alexei Levenkov

Obviously one more way to set something to null is to assign result of function that returns null:

显然,另一种将某些内容设置为 null 的方法是分配返回 null 的函数的结果:

string SomeFunctionThatReturnsNullString() {return null;}

string val = SomeFunctionThatReturnsNullString();

回答by Wesam

assign it to this value will make it a null ,(chose the right sql datatype , here its double )

将其分配给此值将使其成为 null ,(选择正确的 sql 数据类型,此处为 double )

    System.Data.SqlTypes.SqlDouble.Null