Performing a general action on derived types

Is there a neat way to make several classes (which are said to be derived from 1 interface) for each execution of one action? Think of the ASP.NET http modules that serve every request (every keyword) - is there a way to do some general action on derived types? Reflection can be one way, although I would be interested in a method at the base class level.

thanks

+4
source share
6 answers

Not only with an interface; you need an abstract class in the middle:

abstract class Whatever : IFooable { public virtual void Do () { PreDo(); } protected abstract void PreDo(); } 

Then you call Do , and PreDo automatically called first for all implementation types.

(Edit: just to be clear, I did Do virtual, so that means that if you base.Do() it, you must first call base.Do() to make sure that it actually calls the parent method).

+3
source

If your classes all stem from a common base class, you can put this logic in your common base class.

0
source

If I understand correctly what you are asking, maybe an event handler is a way to go?

If you need a bunch of objects to respond to an action, events (also called "messaging") are the way to go.

Something like that?

 class Foo { public event EventHandler PerformAction; private void OnActionNeeded() { // A bunch of Bars need to do something important now. if (PerformAction != null) PerformAction.Invoke(); } } class Bar { public Bar(Foo fooToWatch) { fooToWatch.PerformAction += new EventHandler(Foo_PerformAction); } void Foo_PerformAction(object sender, EventArgs e) { // Do that voodoo that you do here. } } 
0
source

There may not be a complete answer, but I am tempted to think in terms of AOP and attributes.

some links:

http://www.codeproject.com/KB/cs/ps-custom-attributes-1.aspx

http://www.postsharp.org/contributions/documentation/removing-duplicate-code-in-functions

0
source

The design pattern template may apply to what you request.

http://www.dofactory.com/Patterns/PatternTemplate.aspx

0
source

A common point in designing an interface is to provide a protocol between two components and hide part of the implementation. Interfaces serve as a communication medium. And what you ask seems to be implementation specific. Which can be handled using utility classes (singleton with method) I do not suggest having an abstract class in the current ur script.

0
source

Source: https://habr.com/ru/post/1299494/


All Articles