这是原始声明:
[StructLayout(LayoutKind.Explicit, Size = 16)]
public unsafe struct X
{
[FieldOffset(0)] public ushort a;
[FieldOffset(2)] public fixed byte b[14];
};
我想将 struct
设置为只读,但我不知道应该如何为数组编写 getter。我能想到的唯一解决方案是 setter/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 property 而不是 getter method?
===更新===
我还想处理有多个数组字段的情况。例如:
[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 properties 而不是 getter methods?我想写 y.B[i]
和 y.C[i]
而不是 y.B(i)
和 y.C(i)
。
最佳答案
您可以使用索引器属性访问特定索引处的数组。不幸的是,它需要在结构本身而不是 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;
}
}
};
关于c# - 不安全结构中的只读数组字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18185314/