在。net中,String和。net之间的区别是什么?空和"",他们是可交换的,或者有一些潜在的引用或本地化问题,围绕相等的字符串。空将保证都不是问题?


当前回答

谢谢你的回答。

如果我错了,请原谅我的无知。我使用VB,但我认为如果你测试一个未分配的字符串的长度(即IS Nothing),它会返回一个错误。现在,我在1969年开始编程,所以我已经远远落后了,但是我总是通过连接空字符串("")来测试字符串。例:(无论哪种语言):-

如果string + "" = ""

其他回答

上面的答案在技术上是正确的,但你可能真正想要使用的是String.IsNullOrEmpty(s),以获得最好的代码可读性和最小的异常机会。

使用字符串。空而不是""。

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规范。

从实体框架的角度来看:EF版本6.1.3似乎处理字符串。在验证时,Empty和""不同。

字符串。出于验证目的,Empty被视为空值,如果在Required(带属性)字段上使用,则会抛出验证错误;其中as ""将通过验证而不抛出错误。

这个问题可以在EF 7+中解决。参考: - https://github.com/aspnet/EntityFramework/issues/2610)。

编辑:[Required(AllowEmptyStrings = true)]将解决此问题,允许字符串。为空进行验证。

因为字符串。Empty不是编译时常量,不能在函数定义中使用它作为默认值。

public void test(int i=0,string s="")
    {
      // Function Body
    }