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


当前回答

string mystring = "";
ldstr ""

LDSTR将一个新的对象引用推入存储在元数据中的字符串字面值。

string mystring = String.Empty;
ldsfld string [mscorlib]System.String::Empty

LDSFLD将静态字段的值推入计算堆栈

我倾向于使用String。用空代替"",因为在我看来,这样更清晰,也不那么vb。

其他回答

字符串。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和""

当您在视觉上扫描代码时,""会像字符串一样呈现彩色。字符串。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;

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

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

这里的每个人都给出了很好的理论解释。我也有类似的疑问。所以我尝试了一个基本的编码。我发现了不同之处。区别就在这里。

string str=null;
Console.WriteLine(str.Length);  // Exception(NullRefernceException) for pointing to null reference. 


string str = string.Empty;
Console.WriteLine(str.Length);  // 0

所以它似乎“Null”意味着绝对无效和“字符串。“空”表示它包含某种值,但它是空的。