Exemplo n.º 1
0
        public static Instruction EncapsulateWithTryFinally(this ILProcessor ilProcessor)
        {
            var body = ilProcessor.Body;

            var firstInstruction = body.Instructions[0];

            var newReturn = ilProcessor.ReplaceReturnsByLeave();

            var endFinally = Instruction.Create(OpCodes.Endfinally);

            ilProcessor.InsertBefore(newReturn, endFinally);

            if (body.Instructions[0].Equals(firstInstruction))
            {
                Instruction tryStart = Instruction.Create(OpCodes.Nop);
                ilProcessor.InsertBefore(firstInstruction, tryStart);
            }

            Instruction finallyStart = Instruction.Create(OpCodes.Nop);

            ilProcessor.InsertBefore(endFinally, finallyStart);

            var handler = new ExceptionHandler(ExceptionHandlerType.Finally)
            {
                TryStart     = firstInstruction,
                TryEnd       = finallyStart,
                HandlerStart = finallyStart,
                HandlerEnd   = newReturn,
            };

            body.ExceptionHandlers.Add(handler);

            return(endFinally);
        }