在。net中,String和。net之间的区别是什么?空和"",他们是可交换的,或者有一些潜在的引用或本地化问题,围绕相等的字符串。空将保证都不是问题?
当前回答
上面的答案在技术上是正确的,但你可能真正想要使用的是String.IsNullOrEmpty(s),以获得最好的代码可读性和最小的异常机会。
其他回答
从实体框架的角度来看:EF版本6.1.3似乎处理字符串。在验证时,Empty和""不同。
字符串。出于验证目的,Empty被视为空值,如果在Required(带属性)字段上使用,则会抛出验证错误;其中as ""将通过验证而不抛出错误。
这个问题可以在EF 7+中解决。参考: - https://github.com/aspnet/EntityFramework/issues/2610)。
编辑:[Required(AllowEmptyStrings = true)]将解决此问题,允许字符串。为空进行验证。
""的所有实例都是相同的,被分隔的字符串字面量(或者它们应该是)。因此,每次使用""时,实际上不会在堆上抛出一个新对象,而只是创建一个对相同的内部对象的引用。话虽如此,我还是更喜欢字符串。我认为这使代码更具可读性。
使用字符串。空而不是""。
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是一个只读字段,而""是一个编译时常量。他们表现不同的地方有:
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看起来像常规的类成员访问。在快速浏览的过程中,更容易发现“”或凭直觉理解其含义。
找出字符串(堆栈溢出着色不是很有帮助,但在VS中这是更明显的):
var i = 30;
var f = Math.Pi;
var s = "";
var d = 22.2m;
var t = "I am some text";
var e = string.Empty;
推荐文章
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- Printf与std::字符串?
- AppSettings从.config文件中获取值
- 如何检查IEnumerable是否为空或空?
- 不区分大小写的“in”
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 如何在PHP中截断字符串最接近于一定数量的字符?
- 如何在iis7应用程序池中设置。net Framework 4.5版本
- 如何分裂()一个分隔字符串到一个列表<字符串>
- Ruby数组到字符串的转换
- 如何指定最小值,但没有使用范围数据注释属性的最大小数?
- 如何在PowerShell中获得本地主机名?