撒科打诨
实际上,很少有称为Initblk(英文版)的IL操作可以做到这一点。因此,让我们将其用作不需要“不安全”的方法。这是帮助程序类:public static class Util{ static Util() { var dynamicMethod = new DynamicMethod("Memset", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, null, new [] { typeof(IntPtr), typeof(byte), typeof(int) }, typeof(Util), true); var generator = dynamicMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Ldarg_2); generator.Emit(OpCodes.Initblk); generator.Emit(OpCodes.Ret); MemsetDelegate = (Action<IntPtr, byte, int>)dynamicMethod.CreateDelegate(typeof(Action<IntPtr, byte, int>)); } public static void Memset(byte[] array, byte what, int length) { var gcHandle = GCHandle.Alloc(array, GCHandleType.Pinned); MemsetDelegate(gcHandle.AddrOfPinnedObject(), what, length); gcHandle.Free(); } public static void ForMemset(byte[] array, byte what, int length) { for(var i = 0; i < length; i++) { array[i] = what; } } private static Action<IntPtr, byte, int> MemsetDelegate;}表现如何?这是Windows / .NET和Linux / Mono(不同PC)的结果。Mono/for: 00:00:01.1356610Mono/initblk: 00:00:00.2385835 .NET/for: 00:00:01.7463579.NET/initblk: 00:00:00.5953503因此值得考虑。请注意,生成的IL将不可验证。