stackalloc在嵌套上下文中允许Permit stackalloc in nested contexts
堆栈分配Stack allocation
我们修改 c # 语言规范的部分 堆栈分配 ,以便在 stackalloc 可能出现表达式时放松位置。We modify the section Stack allocation of the C# language specification to relax the places when a stackalloc expression may appear. 我们删除We delete
local_variable_initializer_unsafe
: stackalloc_initializer
;
stackalloc_initializer
: 'stackalloc' unmanaged_type '[' expression ']'
;
并将其替换为and replace them with
primary_no_array_creation_expression
: stackalloc_initializer
;
stackalloc_initializer
: 'stackalloc' unmanaged_type '[' expression? ']' array_initializer?
| 'stackalloc' '[' expression? ']' array_initializer
;
请注意,将 array_initializer 添加到 stackalloc_initializer (并使索引表达式可选) 是 c # 7.3 中 的一个扩展,此处未进行描述。Note that the addition of an array_initializer to stackalloc_initializer (and making the index expression optional) was an extension in C# 7.3 and is not described here.
表达式的 元素类型 stackalloc 是 stackalloc 表达式中命名的 unmanaged_type (如果有),或者 array_initializer 的元素中的通用类型,则为; 否则为。The element type of the stackalloc expression is the unmanaged_type named in the stackalloc expression, if any, or the common type among the elements of the array_initializer otherwise.
具有 元素类型 的 stackalloc_initializer 的类型 K 取决于其语法上下文:The type of the stackalloc_initializer with element type K depends on its syntactic context:
- 如果 stackalloc_initializer 直接显示为 local_variable_declaration 语句或 for_initializer 的 local_variable_initializer ,则其类型为
K*。If the stackalloc_initializer appears directly as the local_variable_initializer of a local_variable_declaration statement or a for_initializer, then its type isK*. - 否则,它的类型为
System.Span<K>。Otherwise its type isSystem.Span<K>.
Stackalloc 转换Stackalloc Conversion
Stackalloc 转换 是来自 expression 的新的内置隐式转换。The stackalloc conversion is a new built-in implicit conversion from expression. 当 stackalloc_initializer 的类型为时 K* ,将存在从 stackalloc_initializer 到类型的隐式 stackalloc 转换 System.Span<K> 。When the type of a stackalloc_initializer is K*, there is an implicit stackalloc conversion from the stackalloc_initializer to the type System.Span<K>.