在。net中,String和。net之间的区别是什么?空和"",他们是可交换的,或者有一些潜在的引用或本地化问题,围绕相等的字符串。空将保证都不是问题?
当前回答
使用字符串。空而不是""。
This is more for speed than memory usage but it is a useful tip. The "" is a literal so will act as a literal: on the first use it is created and for the following uses its reference is returned. Only one instance of "" will be stored in memory no matter how many times we use it! I don't see any memory penalties here. The problem is that each time the "" is used, a comparing loop is executed to check if the "" is already in the intern pool. On the other side, String.Empty is a reference to a "" stored in the .NET Framework memory zone. String.Empty is pointing to same memory address for VB.NET and C# applications. So why search for a reference each time you need "" when you have that reference in String.Empty?
参考:字符串。Empty和""
其他回答
当您在视觉上扫描代码时,""会像字符串一样呈现彩色。字符串。Empty看起来像常规的类成员访问。在快速浏览的过程中,更容易发现“”或凭直觉理解其含义。
找出字符串(堆栈溢出着色不是很有帮助,但在VS中这是更明显的):
var i = 30;
var f = Math.Pi;
var s = "";
var d = 22.2m;
var t = "I am some text";
var e = string.Empty;
这里的每个人都给出了很好的理论解释。我也有类似的疑问。所以我尝试了一个基本的编码。我发现了不同之处。区别就在这里。
string str=null;
Console.WriteLine(str.Length); // Exception(NullRefernceException) for pointing to null reference.
string str = string.Empty;
Console.WriteLine(str.Length); // 0
所以它似乎“Null”意味着绝对无效和“字符串。“空”表示它包含某种值,但它是空的。
谢谢你的回答。
如果我错了,请原谅我的无知。我使用VB,但我认为如果你测试一个未分配的字符串的长度(即IS Nothing),它会返回一个错误。现在,我在1969年开始编程,所以我已经远远落后了,但是我总是通过连接空字符串("")来测试字符串。例:(无论哪种语言):-
如果string + "" = ""
使用字符串。空而不是""。
This is more for speed than memory usage but it is a useful tip. The "" is a literal so will act as a literal: on the first use it is created and for the following uses its reference is returned. Only one instance of "" will be stored in memory no matter how many times we use it! I don't see any memory penalties here. The problem is that each time the "" is used, a comparing loop is executed to check if the "" is already in the intern pool. On the other side, String.Empty is a reference to a "" stored in the .NET Framework memory zone. String.Empty is pointing to same memory address for VB.NET and C# applications. So why search for a reference each time you need "" when you have that reference in String.Empty?
参考:字符串。Empty和""
在2.0版本之前的。net中,""创建一个对象while字符串。Empty不会创建objectref,它会生成string。放空更有效率。
在。net 2.0及以后版本中,所有出现的""都指向相同的字符串字面值,这意味着""相当于. empty,但仍然不如. length == 0快。
. length == 0是最快的选项,但是. empty会使代码更简洁。
有关更多信息,请参阅. net规范。
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 我如何提高ASP。NET MVC应用程序性能?
- 我可以将c#字符串值转换为转义字符串文字吗?
- 无法解析类型为“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务
- 如何在没有任何错误或警告的情况下找到构建失败的原因
- Visual Studio弹出提示:“操作无法完成”
- 否ConcurrentList<T>在。net 4.0?
- 在c#中解析字符串为日期时间
- 由Jon Skeet撰写的《Singleton》澄清
- 字符串中的单词大写
- 自定义数字格式字符串始终显示符号