开发者

C# inheritance with views and presenters

I am working with MVP in ASP.NET and wanted see if there is an easier/cleaner way to do this.

I have a presenter with a view. It turns out I can reuse some of the view properties and presenter methods in other views/presenters in the same application area.

Lets say I have a Bar, which is logically a Foo. The base prese开发者_如何转开发nter, FooPresenter, has the common logic for Bar and its siblings. The IFoo view has common properties as well.

I want to be able to treat the view as an IFooView in the FooPresenter, and the view as an IBarView in the BarPresenter and have it be the same instance so I get all of the Foo stuff in my view implementation, the aspx page.

Here is what I have:

public interface IFooView {
    // foo stuff
}

public interface IBarView : IFooView {
    // bar stuff
}

public abstract class FooPresenter<T> where T : IFooView {
    public FooPresenter(T view) {
        this.view = view;
    }

    private IFooView view;
    public T View 
    {
        get { return (T)view; }
    }

    public void SomeCommonFooStuff() { }
}

public class BarPresenter : FooPresenter<IBarView> {
    public BarPresenter (IBarView view) 
        : base(view) {

    }

    public void LoadSomeBarStuff() {
        View.Stuff = SomeServiceCall();
    }
}    

The interesting part is around accessing the view interface in the child class through the property in the base class that does the cast. Any thoughts about this, or recommendations on how I may be able to make this easier to maintain?


The only thing I can see that I would change is to remove the private field in FooPresenter and stick with just the property with a public getter and private setter.

There's no need for the private field in this case, just let the generics do the work for you.


I've done something similar where in the BarPresenter, I'd have a public IBarView View { get { return (IBarView)this.view; } }. Then you can reference the capital View and get what you need.


The private field view could just be declared of type T, that way you avoid unnecessary casts

    private T view;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜