放在哪里常见的接口方法与部分类,继承和Visual Studio生成的代码打交道时 [英] Where to put common interface methods when dealing with partial classes, inheritance, and Visual Studio Generated Code

查看:240
本文介绍了放在哪里常见的接口方法与部分类,继承和Visual Studio生成的代码打交道时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这种情况:



我们已经由Visual Studio生成了两个类,例如,类型化的DataSet行。这些类从一个共同的基类,我们不能改变派生。我们不能改变这些子类的派生类,但它们产生的部分类,所以我们可以扩展它们。



现在我们决定实现这两个类的接口其中定义了一些常用的方法,但这些方法都将被精确地实现在两个类的方式相同。哪里是把这些方法,所以,我们不写相同的代码两次最好的地方。



我可以在一些辅助类或全局类的代码,但它。看起来应该有更好的方式



下面是一个简单的代码示例:

 公共接口ICommonInterface 
{
无效的someMethod(INT X);
}

//我们不能改变什么是在基类中,我们不能从
//不同的基类派生Child1或CHILD2,因为它们是产生局部类Visual Studio的
//我们可以扩展它们,并创建尽管
公共部分类Child1接口:SomeBaseClass,ICommonInterface
{
公共无效的someMethod(INT X)
{
//这个代码是在两个子类
//哪里是把这个以避免写
的最佳地点相同//相同的代码两次
}
}

公共部分类CHILD2:SomeBaseClass,ICommonInterface
{

公共无效的someMethod(INT X)
{
//这个代码是在两个子类
//哪里是把这个以避免写
的最佳地点相同//相同的代码两次
}
}


解决方案

我想在这种情况下使用的封装。创建一个类(在这两个类私有的实例),并委托的someMethod 调用内部私有类实现。



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


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

解决方案

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.

这篇关于放在哪里常见的接口方法与部分类,继承和Visual Studio生成的代码打交道时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆