How to override a base class method that was not overridden by signature

I discovered an interesting thing today. I tried to define the type dynamically with, TypeBuilder

and tried to "override" (ie Replace) the method defined in the base class:

public class Test
{
    public void Method()
    {
        Console.WriteLine("Test from Test");
    }
}

public void Bind(string methodToReplace, Action expr)
{
    @object = Activator.CreateInstance<T>();
    Type objectType = @object.GetType();
    AssemblyBuilder asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("Mock"), AssemblyBuilderAccess.Run);
    ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule("Mock");
    TypeBuilder tB = modBuilder.DefineType(objectType.Name, TypeAttributes.Public | TypeAttributes.Class, objectType);
    var mB = tB.DefineMethod(methodToReplace, MethodAttributes.Public);
    ILGenerator ilGen = mB.GetILGenerator();
    ilGen.EmitCall(OpCodes.Call, expr.GetType().GetMethod("Invoke"), null);
    ilGen.Emit(OpCodes.Ret);
    @object = (T)Activator.CreateInstance(tB.CreateType());
}

      

But, unfortunately, in a certain type there are two methods with the same name "Method", ("t" is an instance of a dynamically defined type):

t.GetType().GetMethods()
{System.Reflection.MethodInfo[6]}
    [0]: {Void Method()}
    [1]: {Void Method()}
    [2]: {System.String ToString()}
    [3]: {Boolean Equals(System.Object)}
    [4]: {Int32 GetHashCode()}
    [5]: {System.Type GetType()}

      

So my question is, how do I add a new method that hides the base class implementation, equivalent to using the C # keyword when defining a new method, e.g .:

public class Test2 : Test
{
    new public void Method()
    {
    }
}

      

+3


source to share


1 answer


You can see two methods because you used type.GetMethods () with no required flags. Try using bindingflags.declaredonly.

You can only see one method. This is exactly what you want.

The new keyword is a C # thing to avoid hiding the base method by mistake.



it will force you to use override or new to avoid the warning.

if you want to override the base merhod use the DefineMethodOverride method in the TypeBuilder.

+1


source







All Articles