公共对象的继承

时间:2015-10-13 09:52:34

标签: c# .net inheritance

我有以下场景,我检索一组BaseObject类型的对象。我根据Object1和Object2类型分割这些对象。

现在我有两个类(Plugin1和Plugin2)根据特定类型处理这些列表,即类型为Object1或类型为Object2。

正如您在代码中看到的,我需要在各自的类中声明不同的列表。

有没有一种方法可以在基类中设置减速度?我仍然需要能够根据各自类别中的类型处理列表,即Plugin1和Plugin2。

public class BaseObject {}
public class Object1 : BaseObject {}
public class Object2 : BaseObject {}

public interface IPlugin
{
    void Process();
}

public class BasePlugin : IPlugin
{
    protected MyManager _manager;        

    public BasePlugin(MyManager manager)
    {
        this._manager = manager;            
    }

    public virtual void Process() { }
}

public class Plugin1 : BasePlugin
{
    private List<Object1> _list;

    public Plugin1(MyManager manager, List<Object1> list)
        : base(manager)
    {
        _list = list;
    }

    public override void Process() 
    {
        base.Process();
    }
}

public class Plugin2 : BasePlugin
{
    private List<Object2> _list;

    public Plugin2(MyManager manager, List<Object2> list)
        : base(manager)
    {
        _list = list;
    }

    public override void Process() 
    {
        base.Process();
    }
}

2 个答案:

答案 0 :(得分:2)

您应该能够使IPlugin接口通用,即

public interface IPlugin<T> where T: BaseObject 
{
    void Process();
}

public class BasePlugin<T> : IPlugin<T>
{
    protected MyManager _manager;        
    protected List<T> _list;

    public BasePlugin(MyManager manager, List<T> list)
    {
        this._manager = manager;    
       _list = list;        
    }

    public virtual void Process() {... }
}

现在,如果Plugin1Plugin2的代码相同,且类型不同,则只会变为:

var plugin1 = new BasePlugin<Object1>();
var plugin2 = new BasePlugin<Object2>();

即。你根本不需要这些类,你可以在声明时指定类型。

答案 1 :(得分:0)

仿制药似乎完成了这项工作。

https://msdn.microsoft.com/en-us/library/512aeb7t.aspx

public abstract class BaseObject {}
public class Object1 : BaseObject {}
public class Object2 : BaseObject {}

public interface IPlugin
{
    void Process();
}

public class BasePlugin<T> : IPlugin where T : BaseObject
{
    protected MyManager _manager;        

    protected List<T> _list;

    public BasePlugin(MyManager manager, List<T> list)
    {
        this._manager = manager;            
        this._list = list;
    }

    public virtual void Process() { }
}

public class Plugin1 : BasePlugin<Object1>
{    
    public Plugin1(MyManager manager, List<Object1> list)
        : base(manager, list) { }

    public override void Process() 
    {
        base.Process();
    }
}

public class Plugin2 : BasePlugin<Object2>
{
    public Plugin2(MyManager manager, List<Object2> list)
        : base(manager, list) { }

    public override void Process() 
    {
        base.Process();
    }
}