处理部分类,inheritance和Visual Studio生成代码时,在何处放置通用接口方法

考虑这种情况:

我们有两个由Visual Studio生成的类,例如Typed Dataset Rows。 这些类派生自一个我们无法改变的公共基类。 我们不能更改这些子类派生的类,但它们是作为部分类生成的,因此我们可以扩展它们。

现在我们决定为这两个类实现一个定义一些常用方法的接口,但这两个类的方法将以完全相同的方式实现。 放置这些方法的最佳位置在哪里,以便我们不会两次编写相同的代码。

我可以在一些辅助类或全局类中使用代码,但似乎应该有更好的方法。

这是一个快速代码示例:

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 } } 

在这种情况下我会使用封装。 创建一个类(在两个类中都有一个私有实例),并将SomeMethod调用委托给内部私有类实现。

这消除了(大多数)重复,同时仍然允许每个类的独特实现的好处。

看起来.NET数据集中包含的TableAdapter类具有可以在设计器中更改的基类。 这是您使用部分类的类,还是可以使用它作为提供这些方法可以使用的公共基类的方法?