gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:48:17 27 4
gpt4 key购买 nike

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

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);
}

?是否保证打印出 0,因为 .NET 中的字符串以 null 结尾?是否所有 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com