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 fromp
top + s.Length - 1
represent addresses of the characters in the string, and the pointer valuep + 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/