c# - How to override method of base class that haven't override in signature -
today discovered interesting thing. tried define type dynamically using typebuilder
, tried 'override' (i.e. replace) method defined in base class:
public class test { public void method() { console.writeline("test 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, unfortunetly, in defined type there two methods same name 'method', ('t' instance of 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 question is: how add new method hides base class's implementation, equivalent using c# 'new' keyword when defining new method, e.g.:
public class test2 : test { new public void method() { } }
you can see 2 methods because used type.getmethods() without bindingflags. try use bindingflags.declaredonly.
you can see 1 method. want to.
new keyword c# thing avoid hiding base method mistake.
it force use override or new avoid warning.
if want override base merhod, use method definemethodoverride on typebuilder.
Comments
Post a Comment