Microsoft 在编写安全高效的 C# 代码中建议:
将
in修改器应用于readonly struct大于的参数System.IntPtr.Size
有没有一种简单的方法来检查像这样的引用结构的托管内存大小ReadOnlySpan<byte>?
以下方法不起作用:
// CS0208 Cannot get the size of a managed type
unsafe { size = sizeof(ReadOnlySpan<byte>); }
// CS0306 The type 'ReadOnlySpan<byte>' may not be used as a type argument
size = Marshal.SizeOf(default(ReadOnlySpan<byte>));
// ArgumentException "must not be a generic type definition"
size = Marshal.SizeOf(typeof(ReadOnlySpan<byte>));
Run Code Online (Sandbox Code Playgroud)
从这个答案来看,IL sizeof指令将返回托管大小,即使对于C# sizeof不接受的类型也是如此,包括通用引用结构类型,如ReadOnlySpan<byte>和Span<byte>。
Type type = typeof(ReadOnlySpan<byte>);
var dm = new DynamicMethod("$", typeof(int), Type.EmptyTypes);
ILGenerator il = dm.GetILGenerator();
il.Emit(OpCodes.Sizeof, type);
il.Emit(OpCodes.Ret);
int size = (int)dm.Invoke(null, null);
Run Code Online (Sandbox Code Playgroud)