探索 C# 和 .NET 中的意外行为
构建强大的应用程序需要深入了解边缘情况。 C# 和 .NET 虽然功能强大,但也呈现出一些挑战常见假设的令人惊讶的场景。让我们看几个例子来说明这些不寻常的行为:
当new
不产生新对象时
考虑这个看似简单的代码:
<code class="language-csharp">string x = new string(new char[0]); string y = new string(new char[0]); Console.WriteLine(object.ReferenceEquals(x, y)); // Prints True</code>
人们可能期望new
始终为引用类型创建不同的对象。 然而,C# 对空字符串的特殊处理导致 x
和 y
引用同一个对象。
可为空类型和 NullReferenceException
此代码片段突出显示了与可空类型的令人费解的交互:
<code class="language-csharp">static void Foo<T>() where T : new() { T t = new T(); Console.WriteLine(t.GetType()); // Throws NullReferenceException }</code>
即使 t
已初始化,调用 GetType()
也会抛出 NullReferenceException
。这是因为如果 T
是可为 null 的类型(如 int?
),则对 object
的隐式装箱可能会导致 null 值,从而在装箱的 null 上调用 GetType()
时导致异常。
空 new
实例
这个场景展示了一种不太直观的可能性:
<code class="language-csharp">public static void CanThisHappen<T>() where T : class, new() { var instance = new T(); // new() on a ref-type; should be non-null Debug.Assert(instance != null, "How did we break the CLR?"); }</code>
约束表明 T
是可以用 new
实例化的引用类型。 然而,像远程处理这样的技术(例如,使用返回 null 的代理)可以绕过这种期望,导致断言失败。 这凸显了处理远程处理等高级功能时引入的复杂性。
以上是为什么一些 C# 和 .NET 极端情况超出预期?的详细内容。更多信息请关注PHP中文网其他相关文章!