Compiler Error CS1708

固定大小的缓冲区只能通过局部变量或字段访问

C# 2.0 的一个新功能是能够在 struct 的内部定义内嵌数组。这类数组只能通过局部变量或字段访问,不能作为表达式左侧的中间值被引用。此外,这些数组无法通过 staticreadonly 的字段访问。

要解决此错误,请定义一个数组变量,然后将内嵌数组分配给该变量。或者,从表示内嵌数组的字段中移除 staticreadonly 修饰符。

下面的示例生成 CS1708。

// CS1708.cs
// compile with: /unsafe
using System;

unsafe public struct S
{
    public fixed char name[10];
}

public unsafe class C
{
    public S UnsafeMethod()
    {
        S myS = new S();
        return myS;
    }

    static void Main()
    {
        C myC = new C();
        myC.UnsafeMethod().name[3] = 'a';  // CS1708
        // Uncomment the following 2 lines to resolve:
        // S myS = myC.UnsafeMethod();
        // myS.name[3] = 'a';

        // The field cannot be static.
        C._s1.name[3] = 'a';  // CS1708

        // The field cannot be readonly.
        myC._s2.name[3] = 'a';  // CS1708
    }

    static readonly S _s1;
    public readonly S _s2;
}