Automatic Method Invocation via Inheritance
I have a large number of classes inheriting from a large number of
interfaces. The interfaces that these classes are implementing do not
share any common methods, but they all share a common first step. An
illustration of this is:
Class A looks like this:
class A : InterfaceA
{
GetFoo(Database db)
{
PerformSetup(db); // This is the common first step.
// Do foo things
}
}
Class B might look something like this:
class B : InterfaceB
{
GetBar(Database db)
{
PerformSetup(db); // This is the common first step.
// Do bar things
}
}
Now obviously I could just create a base class with a method PerformSetup
and have all of these methods call that. But my issue is that there are
very many methods, and that call to PerformSetup() needs to be in all of
them, but it is not yet in any of them.
So I could certainly just copy-paste that setup code to the beginning of
every single method, but in the interest of DRY and my own time, I was
wondering if there was some way I could ensure this method would be
automatically called before any (public-only if possible) method call?
Could I make use of events somehow? Keep in mind again that no class
shares a common interface, and that many of these interface methods have
parameters in addition to the Database parameter, but they all do have the
database parameter.
This probably a bit fantastical but I am always curious to see what crazy
contraptions people are able to rig up in C#.
No comments:
Post a Comment