在。net中,String和。net之间的区别是什么?空和"",他们是可交换的,或者有一些潜在的引用或本地化问题,围绕相等的字符串。空将保证都不是问题?
当前回答
这里的每个人都给出了很好的理论解释。我也有类似的疑问。所以我尝试了一个基本的编码。我发现了不同之处。区别就在这里。
string str=null;
Console.WriteLine(str.Length); // Exception(NullRefernceException) for pointing to null reference.
string str = string.Empty;
Console.WriteLine(str.Length); // 0
所以它似乎“Null”意味着绝对无效和“字符串。“空”表示它包含某种值,但它是空的。
其他回答
字符串。Empty是只读字段,而""是const字段。这意味着您不能使用String。在switch语句中为空,因为它不是常量。
因为字符串。Empty不是编译时常量,不能在函数定义中使用它作为默认值。
public void test(int i=0,string s="")
{
// Function Body
}
这都不重要!
以前的一些讨论:
http://www.codinghorror.com/blog/archives/000185.html
http://blogs.msdn.com/brada/archive/2003/04/22/49997.aspx
http://blogs.msdn.com/brada/archive/2003/04/27/50014.aspx
字符串。Empty不创建对象,而""创建对象。然而,正如这里所指出的,差异是微不足道的。
使用字符串。空而不是""。
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和""
推荐文章
- 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》澄清
- 字符串中的单词大写
- 自定义数字格式字符串始终显示符号