为何“stackalloc”关键字不能与属性的作用? [英] Why does the 'stackalloc' keyword not work with properties?
问题描述
我最近写一些不安全code在C#中,注意到这将产生一个语法错误:
公众安全的类UnsafeByteStream
{
公共UnsafeByteStream(INT容量)
{
this.Buffer = stackalloc字节[容量]
}
公共字节*缓冲区{获得; }
}
这样做的结果是:无效EX pression术语stackalloc'/;预计/}预计
。然而,当我将这个第一次到当地现场,像这样:
公共UnsafeByteStream(INT容量)
{
字节*缓冲区= stackalloc字节[容量]
this.Buffer =缓冲区;
}
那么有没有语法错误产生。
有一个原因,或者是一些与编译器?据我所知,指针型属性是不是所有的常见的,但我还是不明白为什么这是一个的语法的,而不是错误的语义的之一,承担什么是错的与code。
stackalloc
的必须的是局部变量声明的一部分,<一个HREF =https://msdn.microsoft.com/en-us/library/cx9s2sy4.aspx相对=nofollow>在文档讨论。</ P>
在[stackalloc]关键字是只适用于局部变量的初始化的。下面code使编译器错误。
INT *块; //下面赋值语句会导致编译器错误。您 声明和初始化一个地方,只有当//可以使用stackalloc // 变量。 块= stackalloc INT [100];
因此,它确实是一个语法错误;并拒绝 obj.Property = stackalloc ..
的形式。
(后来分配到一个属性是 - 未捕获 - 语义错误)
I was writing some unsafe code recently in C# and noticed this produces a syntax error:
public unsafe class UnsafeByteStream
{
public UnsafeByteStream(int capacity)
{
this.Buffer = stackalloc byte[capacity];
}
public byte* Buffer { get; }
}
The result of this is: "Invalid expression term 'stackalloc' / ; expected / } expected"
. However, when I assign this first to a local field, like so:
public UnsafeByteStream(int capacity)
{
byte* buffer = stackalloc byte[capacity];
this.Buffer = buffer;
}
Then there is no syntax error produced.
Is there a reason for this, or is something up with the compiler? I understand that pointer-type properties are not all that common, but I still don't understand why this is a syntax error as opposed to a semantic one, assuming something's wrong with the code.
stackalloc
must be part of the local variable declaration, as discussed in the documentation.
The [stackalloc] keyword is valid only in local variable initializers. The following code causes compiler errors.
int* block; // The following assignment statement causes compiler errors. You // can use stackalloc only when declaring and initializing a local // variable. block = stackalloc int[100];
As such it truly is a syntax error; and rejects the obj.Property = stackalloc ..
form.
(The later assignment to a property is an - uncaught - semantic error.)
这篇关于为何“stackalloc”关键字不能与属性的作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!