Hiro.Compilers.MethodOverrider.AddOverrideFor C# (CSharp) Method

AddOverrideFor() public method

Adds a method override for a particular targetMethod.
public AddOverrideFor ( MethodInfo targetMethod, Mono.Cecil.TypeDefinition hostType ) : Mono.Cecil.MethodDefinition
targetMethod System.Reflection.MethodInfo The target method.
hostType Mono.Cecil.TypeDefinition The type that will host the new method.
return Mono.Cecil.MethodDefinition
        public MethodDefinition AddOverrideFor(MethodInfo targetMethod, TypeDefinition hostType)
        {
            var module = hostType.Module;
            var options = new MethodBuilderOptions();

            options.IsPublic = true;
            options.MethodName = targetMethod.Name;

            var parameterTypes = new List<System.Type>();
            foreach (var param in targetMethod.GetParameters())
            {
                parameterTypes.Add(param.ParameterType);
            }

            options.HostType = hostType;
            options.SetMethodParameters(parameterTypes.ToArray());
            options.ReturnType = targetMethod.ReturnType;

            var builder = new MethodBuilder();
            return builder.CreateMethod(options);
        }

Usage Example

        /// <summary>
        /// Overrides the target <paramref name="method"/> with a method that throws a <see cref="NotImplementedException"/>.
        /// </summary>
        /// <param name="type">The target type.</param>
        /// <param name="module">The host module.</param>
        /// <param name="overrider">The <see cref="MethodOverrider"/> that will be used to override the target method.</param>
        /// <param name="method">The target method.</param>
        /// <returns>The stubbed method.</returns>
        private static MethodDefinition CreateMethodStub(TypeDefinition type, ModuleDefinition module, MethodOverrider overrider, MethodInfo method)
        {
            // Import the NotImplementedException type
            var notImplementedCtor = module.ImportConstructor<NotImplementedException>();
            var currentMethod = overrider.AddOverrideFor(method, type);

            // Create the method stub
            var body = currentMethod.Body;
            var il = body.GetILProcessor();

            il.Emit(OpCodes.Newobj, notImplementedCtor);
            il.Emit(OpCodes.Throw);

            return currentMethod;
        }
All Usage Examples Of Hiro.Compilers.MethodOverrider::AddOverrideFor
MethodOverrider