我正在玩stackalloc
并发现它的返回类型有很多奇怪之处。以下是一些使用示例stackalloc<float>
:
1.隐式输入返回float*
:
var a = stackalloc float[1];//a is float*
2.声明 afloat*
并稍后设置它 usingstackalloc
不会编译:
float* a;
a = stackalloc float[1];//CS8346 conversion of a stackallock expression of type 'float' to type 'float*' is not possible
3.float*
在初始化的同时声明就可以了:
float* a = stackalloc float[1];
4.类似的行为发生在Span<float>
这工作得很好:
Span<float> a = stackalloc float[1];
但这不会编译:
Span<float> a;
a = stackalloc float[1];//CS8353 A result of a stackalloc expression of type 'Span<float>' cannot be used in this context because it may be exposed outside of the containing method
5.Span<float>
使整个情况更加奇怪的是, and or之间没有隐式转换,float*
反之亦然。
那么返回的究竟是什么stackalloc float[1]
?为什么会出现上述行为?
此代码是使用 VS 2019 C# 版本 9.0、.NET 5 编写的。