在 C# 中使用索引器访问 "this" pointer/reference
Accessing "this" pointer/reference using an indexer in C#
我正在为代码库的性能/内存关键部分试验数据结构。我想快速访问结构中定义的字节。但是我不确定如何使用索引器访问我正在操作的结构。
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Foo
{
[SerializeField]
private byte a, b, c;
public unsafe byte this[byte index]
{
get
{
//omitted safety checks
//this is a no, no
byte* addr = (byte*)&this;
return addr[index];
}
}
}
你只能在 fixed
块中做你想做的事情,即:
fixed (Foo* foo = &this)
{
byte* addr = (byte*)foo;
return addr[index];
}
我正在为代码库的性能/内存关键部分试验数据结构。我想快速访问结构中定义的字节。但是我不确定如何使用索引器访问我正在操作的结构。
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Foo
{
[SerializeField]
private byte a, b, c;
public unsafe byte this[byte index]
{
get
{
//omitted safety checks
//this is a no, no
byte* addr = (byte*)&this;
return addr[index];
}
}
}
你只能在 fixed
块中做你想做的事情,即:
fixed (Foo* foo = &this)
{
byte* addr = (byte*)foo;
return addr[index];
}