C#多重继承替换

时间:2015-08-05 22:52:00

标签: c# wpf multiple-inheritance

我在C#中寻找或更好的方法,否则将是一个简单的多继承模式。

我有继承自WPF的Window类的Master和Slave窗口,我希望它们都具有另一个通用接口/功能。 我首先想到的是实现一个将继承自Window的BaseWindow类,Slave和Master都会继承,
但由于WPF中的一些问题,它们(主窗口和从窗口)必须直接从Window(NOT BaseWindow)继承
那么我定义了一个像这样的界面

public interface MasterOrSlaveWindow
{
    View CurrentView { get; set; }
}

Master和Slave都实现了它:

public partial class SlaveWindwow : Window, MasterOrSlaveWindow
{
    protected View m_CurrentView = null;
    public View CurrentView { 
        get { return m_CurrentView; } 
        set 
        {
            if (value == null && m_CurrentView != null)
                m_CurrentView.Owner = null;

            m_CurrentView = value; 

            if (m_CurrentView != null) 
                m_CurrentView.Owner = this;
        } 
    }
}

它适用于实现不同的情况,但对于相同的情况,我们有代码重复:

public partial class MasterWindwow : Window, MasterOrSlaveWindow
{
    protected View m_CurrentView = null;
    public View CurrentView { 
        get { return m_CurrentView; } 
        set 
        {
            if (value == null && m_CurrentView != null)
                m_CurrentView.Owner = null;

            m_CurrentView = value; 

            if (m_CurrentView != null) 
                m_CurrentView.Owner = this;
        } 
    }
}

在这种情况下,避免代码重复的好方法是什么?

1 个答案:

答案 0 :(得分:0)

也许像这样使用类似DI的风格:

public interface IWindowHandler
{
    View GetCurrentView();
}

public class MasterWindowHandler : IWindowHandler
{
    public View GetCurrentView()
    {
    }
}

public class SomeOtherWindowHandler : IWindowHandler
{

    public View GetCurrentView()
    {
    }
}

// all your windows should inherit from this type
public class MyBaseWindow : Window
{

    protected IWindowHander _handler;

    public MyBaseWindow(IWindowHandler handler)
    {
        _handler = handler;
    }

    protected View m_CurrentView = null;

    public View CurrentView 
    { 
        get { return m_CurrentView; } 
        set 
        {
            // your code
        }
    } 
}

// a sample window code
public partial class MasterWindow : MyBaseWindow 
{
    public MasterWindow(IWindowHandler handler) : base(handler)
    {
    }
}

当然你必须在窗口的实例化中注意,但是你可以轻松地改变实现而不触及窗口本身。

using (var window = new MasterWindow(new MasterWindowHandler()))
{

}