在。net中,String和。net之间的区别是什么?空和"",他们是可交换的,或者有一些潜在的引用或本地化问题,围绕相等的字符串。空将保证都不是问题?
当前回答
string mystring = "";
ldstr ""
LDSTR将一个新的对象引用推入存储在元数据中的字符串字面值。
string mystring = String.Empty;
ldsfld string [mscorlib]System.String::Empty
LDSFLD将静态字段的值推入计算堆栈
我倾向于使用String。用空代替"",因为在我看来,这样更清晰,也不那么vb。
其他回答
使用字符串。空而不是""。
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是一个只读字段,而""是一个编译时常量。他们表现不同的地方有:
c# 4.0或更高版本中的默认参数值
void SomeMethod(int ID, string value = string.Empty)
// Error: Default parameter value for 'value' must be a compile-time constant
{
//... implementation
}
switch语句中的大小写表达式
string str = "";
switch(str)
{
case string.Empty: // Error: A constant value is expected.
break;
case "":
break;
}
属性参数
[Example(String.Empty)]
// Error: An attribute argument must be a constant expression, typeof expression
// or array creation expression of an attribute parameter type
因为字符串。Empty不是编译时常量,不能在函数定义中使用它作为默认值。
public void test(int i=0,string s="")
{
// Function Body
}
在2.0版本之前的。net中,""创建一个对象while字符串。Empty不会创建objectref,它会生成string。放空更有效率。
在。net 2.0及以后版本中,所有出现的""都指向相同的字符串字面值,这意味着""相当于. empty,但仍然不如. length == 0快。
. length == 0是最快的选项,但是. empty会使代码更简洁。
有关更多信息,请参阅. net规范。
推荐文章
- 我如何使一个方法的返回类型泛型?
- 如何获取正在执行的程序集版本?
- AutoMapper vs valueinjector
- 什么是.NET程序集?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- 函数应该返回空对象还是空对象?
- 如何转换日期时间?将日期时间
- 如何删除表中特定列的第一个字符?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 将整数转换为字符串,以逗号表示千
- 转换为值类型'Int32'失败,因为物化值为空
- 将JavaScript字符串中的多个空格替换为单个空格
- c#中有任何连接字符串解析器吗?
- printf()和puts()在C语言中的区别是什么?