重学c#系列——string.empty 和 "" 还有null[二十]

2022-12-12,,,,

前言

简单整理一下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的区别。

重学c#系列——string.empty 和 "" 还有null[二十]的相关教程结束。

《重学c#系列——string.empty 和 "" 还有null[二十].doc》

下载本文的Word格式文档,以方便收藏与打印。