3

这是原始声明:

[StructLayout(LayoutKind.Explicit, Size = 16)]
public unsafe struct X
{
  [FieldOffset(0)] public ushort a;
  [FieldOffset(2)] public fixed byte b[14];
};

我想让struct只读,但我不知道我应该如何为数组编写一个吸气剂。我能想到的唯一解决方案是 getter方法

[StructLayout(LayoutKind.Explicit, Size = 16)]
public unsafe struct X
{
  [FieldOffset(0)] private ushort a;
  [FieldOffset(2)] private fixed byte b[14];

  public ushort A { get { return a; } }
  public byte B(int i) { fixed (byte* p = b) { return p[i]; } }
};

是否可以为 b 编写 getter属性而不是 getter方法

=== 更新 ===

当有多个数组字段时,我也想处理这种情况。例如:

[StructLayout(LayoutKind.Explicit, Size = 24)]
public unsafe struct Y
{
  [FieldOffset(0)] private ushort a;
  [FieldOffset(2)] private fixed byte b[14];
  [FieldOffset(16)] private fixed byte c[8];

  public ushort A { get { return a; } }
  public byte B(int i) { fixed (byte* p = b) { return p[i]; } }
  public byte C(int i) { fixed (byte* p = c) { return p[i]; } }
};

是否可以为 b 和 c 编写 getter属性而不是 getter方法?我想写y.B[i]andy.C[i]而不是y.B(i)and y.C(i)

4

2 回答 2

3

您可以使用索引器属性来访问特定索引处的数组。不幸的是,它需要在结构本身而不是 B 上定义,但这应该提供您正在寻找的内容:

[StructLayout(LayoutKind.Explicit, Size = 16)]
public unsafe struct X
{
    [FieldOffset(0)]
    private ushort a;
    [FieldOffset(2)]
    private fixed byte b[14];

    public ushort A { get { return a; } }
    public byte this [int i]
    {
        get 
        {
            byte b1;
            fixed (byte* b2 = b)
            {
                b1 = b2[i];
            }
            return b1;
        }
    }
 }; 
于 2013-08-12T11:15:57.290 回答
1

我找到了一个解决方案,它基于索引属性的思想:

[StructLayout(LayoutKind.Explicit, Size = 14)]
public struct YB
{
  [FieldOffset(0)] private fixed byte b[14];
  public byte this[int i] { get { fixed (byte* p = b) { return p[i]; } } }
}

[StructLayout(LayoutKind.Explicit, Size = 8)]
public struct YC
{
  [FieldOffset(0)] private fixed byte c[8];
  public byte this[int i] { get { fixed (byte* p = c) { return p[i]; } } }
}

[StructLayout(LayoutKind.Explicit, Size = 24)]
public unsafe struct Y
{
  [FieldOffset(0)] private ushort a;
  [FieldOffset(2)] private YB b;
  [FieldOffset(16)] private YC c;

  public ushort A { get { return a; } }
  public YB B { get { return b; } }
  public YC C { get { return c; } }
};
于 2013-08-12T11:46:38.910 回答