Call a method each time before any other method is called
I have a class where inside this class is one pri开发者_运维问答vate method and many public methods. This private method must be called every time before any other method is called.
The simpliest approach would be calling the method in every method, but I don't like this approach. Is there any other way to achieve this ?
You might be able to do something here with AOP, perhaps via PostSharp; but unles you are going to do this lots, I'd argue in favor of keeping it simple, and just add the extra code.
Of course, it gets more complex if you need polymorphism and need overrides to still call the method first (probably involving a public non-virtual method and a protected virtual method):
public void Foo() {
Bar()
FooCore();
}
protected virtual void FooCore() {...} // default Foo implementation
private void Bar() {...} // your special code
This is a typical case of aspect oriented programming. As far as I know, there is no easy way to do this in .NET (except using byte-code enhancement or creation of a derived class at runtime, neither is easy. There are libraries doing it, for instance spring.net. I'm not sure if you really need this.)
I would try to avoid this situation at almost every cost - or call this method if there is really no other way.
精彩评论