重学c#系列——string.empty 和 "" 还有null[二十]
前言
简单整理一下string.empty 和 "" 还有 null的区别。
正文
首先null 和 string.empty 还有 "" 是不一样的。
null 关键字是表示不引用任何对象的空引用的文字值。 null 是引用类型变量的默认值。
我们编辑高级语言的时候就可以表示的含义就是不引用任何对象的空引用。
但也不能完全这样说,应该说在语法含义上是这样的,具体的肯定指向某个引用。
string.empty 和 "" 实际上是一样的。
// The Empty constant holds the empty string value. It is initialized by the EE during startup.
// It is treated as intrinsic by the JIT as so the static constructor would never run.
// Leaving it uninitialized would confuse debuggers.
//
//We need to call the String constructor so that the compiler doesn't mark this as a literal.
//Marking this as a literal would mean that it doesn't show up as a field which we can access
//from native.
public static readonly String Empty;
也可以进行测试:
static void Main(string[] args)
{
string a = string.Empty;
string b = string.Empty;
string c = "";
Console.WriteLine(object.ReferenceEquals(a, b));
Console.WriteLine(object.ReferenceEquals(a,c));
Console.ReadKey();
}
这样可以看出其实是一样的,这其实是一个string 常量池的作用了。
结
下一节介绍DateTime和DateTimeOffset的区别。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步