[英]Nothing equals String.Empty, null does not equal String.Empty, what am I missing here?
[英]Can string.Empty ever be equal to null?
我发现了一个用C#
编写的开源操作系统代码,我看到了以下检查:
if (String.Empty == null)
throw new Exception("Compiler didn't initialize System.String.Empty!");
它对我来说看起来像一个毫无意义的检查但是因为我在操作系统的源代码中看到它,我以为我可能会遗漏一些东西。 string.Empty
可能为null吗?
注意:如果您有兴趣,请参阅以下源代码
根据MSDN :
String .Empty == ""
来自referencesource.microsoft.com :
// 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.
. . . .
public static readonly String Empty;
(EE可能意味着“ 执行引擎 ”。)
当然,可能是某些CLR实现不遵循此规则,或者有人设法使用Reflection来破解它。 但如果我们考虑这样的情况,那么答案就应该接近“一切皆有可能”。
它可以? 是。
这行代码会告诉你它是不是? 不可靠。 一旦打破运行时的不变量,所有代码的行为就变得不可靠。
这条线更有可能成功执行测试,但仍然没有保证:
if (ReferenceEquals(null, typeof(string).GetField("Empty").GetValue(null)))
在正常环境中,这可能(或更好地说应该 )永远不会出现这种情况(除了运行时中的错误,或者有人反思),因为String.Empty
被指定为等于""
。
由于您所指的项目(AtomOS)正在使用IL2CPU将IL代码转换为本机机器指令,因此可能会用于捕获IL2CPU中的错误。
根据标准,不, string.Empty
永远不应为null。
但是,这可能使用自定义C#编译器来编写操作系统。 我认为这个测试在单元测试中会更好,但那只是我。
在正常的应用程序中,no,String.Empty永远不能为null。
异常消息似乎表明开发人员认为编译器是初始化AtomOS的String.Empty,但这没有意义...... String.Empty在运行时由静态构造函数初始化,而不是在编译时。
我不知道在AtomOS中String.Empty是否可能为null,但一般情况下,除非System.String的运行时或实现是错误的,否则它是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.