在。net中,String和。net之间的区别是什么?空和"",他们是可交换的,或者有一些潜在的引用或本地化问题,围绕相等的字符串。空将保证都不是问题?
当前回答
另一个区别是字符串。Empty生成更大的CIL代码。而用于引用“”和String的代码。Empty是相同的长度,编译器不会为string优化字符串连接(参见Eric Lippert的博客文章)。空的参数。以下等价函数
string foo()
{
return "foo" + "";
}
string bar()
{
return "bar" + string.Empty;
}
生成这个IL
.method private hidebysig instance string foo() cil managed
{
.maxstack 8
L_0000: ldstr "foo"
L_0005: ret
}
.method private hidebysig instance string bar() cil managed
{
.maxstack 8
L_0000: ldstr "bar"
L_0005: ldsfld string [mscorlib]System.String::Empty
L_000a: call string [mscorlib]System.String::Concat(string, string)
L_000f: ret
}
其他回答
使用字符串。空而不是""。
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和""
从实体框架的角度来看:EF版本6.1.3似乎处理字符串。在验证时,Empty和""不同。
字符串。出于验证目的,Empty被视为空值,如果在Required(带属性)字段上使用,则会抛出验证错误;其中as ""将通过验证而不抛出错误。
这个问题可以在EF 7+中解决。参考: - https://github.com/aspnet/EntityFramework/issues/2610)。
编辑:[Required(AllowEmptyStrings = true)]将解决此问题,允许字符串。为空进行验证。
在2.0版本之前的。net中,""创建一个对象while字符串。Empty不会创建objectref,它会生成string。放空更有效率。
在。net 2.0及以后版本中,所有出现的""都指向相同的字符串字面值,这意味着""相当于. empty,但仍然不如. length == 0快。
. length == 0是最快的选项,但是. empty会使代码更简洁。
有关更多信息,请参阅. net规范。
字符串。Empty不创建对象,而""创建对象。然而,正如这里所指出的,差异是微不足道的。
我倾向于使用String。空而不是"",原因很简单,但并不明显: “”和“”是不一样的,第一个实际上有16个零宽度字符。显然,没有一个有能力的开发人员会在他们的代码中放入零宽度字符,但如果他们真的这样做了,那将是一个维护的噩梦。
注:
在这个例子中,我使用了U+FEFF。 不确定SO是否会吃掉这些字符,但请自己尝试使用许多零宽度字符中的一个 多亏了https://codegolf.stackexchange.com/,我才发现了这一点
推荐文章
- 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》澄清
- 字符串中的单词大写
- 自定义数字格式字符串始终显示符号