Where to put common interface methods when dealing

2019-02-20 19:42发布

Consider this situation:

We have two classes generated by Visual Studio, for example Typed Dataset Rows. These classes derive from a common base class which we cannot change. We cannot change the class these child classes derive from, but they are generated as partial classes so we can extend them.

Now we decide to implement an interface for these two classes which define some common methods, but the methods are going to be implemented exactly the same way in both classes. Where is the best place to put these methods so that we are not writing the same code twice.

I could the the code in some helper class or global class, but it seems like there should be a better way.

Here is a quick code example:

public interface ICommonInterface
{
    void SomeMethod(int x);
}

// we cannot change what is in the base class and we cannot derive Child1 or Child2 from
// a different base class, because they are partial classes generated by Visual Studio
// we can extend them, and create an interface though
public partial class Child1: SomeBaseClass, ICommonInterface
{
    public void SomeMethod(int x)
    {
        //this code is the same in both child classes
        //where is the best place to put this to avoid writing 
        //the same code twice
    }
}

public partial class Child2: SomeBaseClass, ICommonInterface
{

    public void SomeMethod( int x)
    {
        //this code is the same in both child classes
        //where is the best place to put this to avoid writing 
        //the same code twice
    }
}

2条回答
Anthone
2楼-- · 2019-02-20 20:25

I would use encapsulation in this case. Create a class (with a private instance in both classes), and delegate the SomeMethod call to the internal, private class implementation.

This eliminates (most) of the duplication, while still allowing the benefits of unique implementations per class as necessary.

查看更多
乱世女痞
3楼-- · 2019-02-20 20:29

It looks like the TableAdapter classes contained in .NET datasets has a base class that can be changed in teh designer. Is this the class you are using with partial classes, or could you use this as a way to provide a common base class where these methods could go?

查看更多
登录 后发表回答