简体   繁体   English

为什么'stackalloc'关键字不适用于属性?

[英]Why does the 'stackalloc' keyword not work with properties?

I was writing some unsafe code recently in C# and noticed this produces a syntax error: 我最近在C#中编写了一些不安全的代码,并注意到这会产生语法错误:

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" . 结果是: "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 . stackalloc 必须是局部变量声明的一部分,如文档中所述

The [stackalloc] keyword is valid only in local variable initializers . [stackalloc]关键字仅在局部变量初始值设定项中有效 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. 并拒绝obj.Property = stackalloc ..表单。

(The later assignment to a property is an - uncaught - semantic error.) (后来对属性的赋值是 - 未捕获 - 语义错误。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM