What is the best practice for an alternative Multi-Inheritance solution in C #

I have some classes inherited from existing Windows controls like TextBox and DateTimePicker, .. etc

I want to add custom functions for these classes, for example (Read, Alert, ... etc.). these extra features are the same in all these classes

The problem is this: these classes are inherited from the differences parents, so I cannot add my extra functions to the parent class,

What is the best practice in this case:

  • repeat the code in each inherited class

  • Using a shared class has functionality like static methods with a parameter from an interface, implement this interface for classes and then pass them.

  • Use the highlighted class as a second approach, but with the Dynamic parameter (which is added in C # 4.0)

    or another !!

Thanks in advance

+5
source share
4 answers

I would consider option 4: composition.

Define your feature set first. We will assume that your partial list is exclusive, therefore "Read" and "Warning."

Secondly, create one class that implements this functionality, for example MyCommonControlBehaviors. I would prefer that this implementation is not static, if possible, although it may be general.

public MyCommonControlBehaviors
{
    public Whatever Read() { /* ... */ }
    public void Alert() {}
}

-, , :

public class MyCustomControl
{
    private MyCommonControlBehaviors common; // Composition

    public Whatever Read() { return this.common.Read(); }
    public void Alert() { this.common.Alert(); }
}

. , , . ICommonBehaviorHost, . ICommonBehaviorHost:

public interface ICommonBehaviorHost
{
    void Notify();
}

public class MyCommonControlBehaviors
{
    ICommonBehaviorHost hst = null;

    public MyCommonControlBehaviors(ICommonBehaviorHost host) 
    {
        this.hst = host;
    }

    public void Alert() { this.hst.Notify(); }  // Calls back into the hosting control
    // ...
}

public class MyCustomControl : ICommonBehaviorHost
{
    private MyCommonControlBehaviors common = null;

    public MyCustomControl() { common = new MyCommonControlBehaviors(this); }
    public Whatever Read() { return this.common.Read(); }
    public void Alert() { this.common.Alert(); }

    void ICommonBehaviorHost.Notify() { /* called by this.common */ }
}
+12

!

+6

, , , , , , , , , .

, , , .

, : Functions.DoSomething(my_Object);

: my_Object.DoSomething() OO.

+1
source

I would suggest defining an interface for behavior, and then (so as not to repeat myself) create extension methods in this interface definition for your common methods. (It seems like your second option, only with extension methods instead of fully static methods).

0
source

All Articles