C#:固定语句对空字符串的行为是什么?

标签 c# string mono clr unsafe

This document是 C# 语言规范的一部分,它表示如果在 null/空数组引用上使用固定的行为,则 C# 中的固定行为是实现定义的。引用它:

An expression of an array-type with elements of an unmanaged type T, provided the type T* is implicitly convertible to the pointer type given in the fixed statement. In this case, the initializer computes the address of the first element in the array, and the entire array is guaranteed to remain at a fixed address for the duration of the fixed statement. The behavior of the fixed statement is implementation-defined if the array expression is null or if the array has zero elements.

但是,它不会对空字符串做出相同的声明,只是说如果字符串为 null,则不会定义该行为。下一段详细介绍了它如何适用于字符串:

An expression of type string, provided the type char* is implicitly convertible to the pointer type given in the fixed statement. In this case, the initializer computes the address of the first character in the string, and the entire string is guaranteed to remain at a fixed address for the duration of the fixed statement. The behavior of the fixed statement is implementation-defined if the string expression is null.

因此,如果我正确地阅读了此内容,这意味着该行为是为空字符串定义的,对吗?那么,如果你做类似的事情,会发生什么

fixed (char* pch = string.Empty)
{
    Console.WriteLine((int)*pch);
}

?由于 .NET 中的字符串以 null 结尾,是否保证打印出 0?所有 ECMA 335 实现(例如 Microsoft 的 CLR、Mono)都要求字符串以 null 结尾吗?

谢谢。

最佳答案

是的,由于 18.6 后面的一位,它保证打印出 0:

A char* value produced by fixing a string instance always points to a null-terminated string. Within a fixed statement that obtains a pointer p to a string instance s, the pointer values ranging from p to p + s.Length - 1 represent addresses of the characters in the string, and the pointer value p + s.Length always points to a null character (the character with value '\0').

我不能说我在 Mono 上尝试过这个,但如果是这样的话,这肯定是一个不合规问题。 ECMA 标准中的文本与 MS 规范中的文本相同。 (C# 2 版本中的第 27.6 条;看起来 C# 5 版本中的第 24.7 条。)

关于C#:固定语句对空字符串的行为是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37757751/

相关文章:

java - 如果使用 new 运算符创建对象,为什么要在 String 中使用 intern 方法?

.net - Autofac 3.0 不能在 Mono 上运行

c# - Visual Studio 的 Web 性能测试可以用作 Web 场的压力测试吗?

c# - c#捕获鼠标点击事件

swift - 将字符串转换为日期会分配错误的值

c# - 替换 C# 字符串中的数字

c# - 声明字段和构造函数注入(inject)的最快方法

c# - 何时使用 System.Threading.ThreadPool 以及何时使用众多自定义线程池之一?

c# - 在单声道中编译时 C# List 的问题(与作业相关)

c# - Linux Mono 中使用快速彩色文本框的 System.NullReferenceException