c# - pre and post actions to an existing class method -
i’m novice in c# , need help. need implement series of wrappers functions perform pre , post action besides original method.
this way (one function example):
class { public streamwriter writer; public bool writeln(string texttowrite)//wrapper writer.write(string) { preaction(); this.writer.write(texttowrite); postaction(); } }
related scenarios - tracing each function entry (so signature of post , pre void post() , iterating method parameters through reflection).
i need done on numerous classes , functions- wrapping each 1 tedious, if change need reopen code many times. solution can think of (instead of composition-see attached code above) inheriting streamwriter , overriding base method, again multiple classes , functions isn’t pretty, can think or know of different way doing that?
br, mosh.
you write wrapper class , either pass constructor of class want wrap methods of, or have class create wrapper class itself.
it still rather fiddly, let put wrapper logic 1 class.
an example clarify. class demo
shows how use wrapper class. note wrapper class allows detect exceptions (while ensuring exceptions still thrown).
argument-checking logic omitted brevity:
using system; using system.io; namespace consoleapp1 { public sealed class wrapper { public wrapper(action pre, action<exception> post) { _pre = pre; _post = post; } public t wrap<t>(func<t> func) { try { _pre(); t result = func(); _post(null); return result; } catch (exception exception) { _post(exception); throw; } } public void wrap(action action) { try { _pre(); action(); _post(null); } catch (exception exception) { _post(exception); throw; } } private readonly action _pre; private readonly action<exception> _post; } public sealed class demo { public demo(wrapper wrapper) { _wrapper = wrapper; } public string name() { return _wrapper.wrap(() => "this name"); } public void write(string texttowrite) { _wrapper.wrap(() => _writer.write(texttowrite)); } public void throwsexception() { _wrapper.wrap(() => {throw new invalidoperationexception("test");}); } private readonly wrapper _wrapper; private readonly streamwriter _writer = new streamwriter(console.openstandardoutput()); } sealed class program { private void run() { var wrapper = new wrapper ( () => console.writeline("calling pre()"), ex => console.writeline("calling post(), exception = " + ((ex != null) ? ex.message : "<none>")) ); demo demo = new demo(wrapper); console.writeline("name = " + demo.name()); demo.write("some text write"); demo.throwsexception(); } private static void main() { new program().run(); } } }
Comments
Post a Comment