不安全结构中的只读数组字段

时间:2013-08-12 11:01:15

标签: c# arrays properties getter unsafe

这是原始声明:

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

我想将struct设为只读,但我不知道应该如何编写数组的getter。我能想出的唯一解决方案是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]y.C[i]而不是y.B(i)y.C(i)

2 个答案:

答案 0 :(得分: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;
        }
    }
 }; 

答案 1 :(得分:1)

我找到了一个解决方案,它基于indexed properties

的想法
[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; } }
};