public interface IBasePresenter
{
}
public interface IJobViewPresenter : IBasePresenter
{
}
public interface IActivityViewPresenter : IBasePresenter
{
}

public class BaseView
{
    public IBasePresenter Presenter
    {
        get;
        set;
    }
}

public class JobView : BaseView
{
    public IJobViewPresenter JobViewPresenter
    {
        get { this.Presenter as IJobViewPresenter;}
    }
}

public class ActivityView : BaseView
{
    public IActivityViewPresenter ActivityViewPresenter
    {
        get { this.Presenter as IActivityViewPresenter;}
    }
}

假设我在BaseView上需要IBasePresenter属性。
现在,此属性由JobView和ActivityView继承,但是如果我需要在这些派生类中引用IJobViewPresenter对象,则需要将IBasePresenter属性转换为IJobViewPresenter或IActivityPresenter(我要避免),或者在派生类上创建JobViewPresenter和ActivityViewPresenter(如如上所示)。

我想避免在派生类中进行类型转换,并且仍然引用IJobViewPresenter或IActivityViewPresenter,并且在BaseView中仍然具有IBasePresenter。

有办法可以实现吗?

最佳答案

你可以这样做:

    public class BaseView<TPresenter>
        where TPresenter: IBasePresenter
    {
        TPresenter Presenter { get; set; }
    }

    public class JobView: BaseView<IJobViewPresenter>
    {

    }

如果您有需要引用BaseView的代码,则可以创建一个接口(interface)并公开基本演示者,如下所示:
    public interface IBaseView
    {
        IBasePresenter BasePresenter { get; }
    }

    public class BaseView<TPresenter> : IBaseView
        where TPresenter: IBasePresenter
    {
        TPresenter Presenter { get; set; }

        IBasePresenter IBaseView.BasePresenter
        {
            get { return Presenter; }
        }
    }

现在,需要访问BaseView的类可以直接使用该接口(interface),而不是使用BaseView。您也可以在其中公开需要使用的任何其他基本服务。

关于c# - 设计以避免在派生类中进行类型转换?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2567957/

10-13 02:00