2008-12-12 55 views
5

我想爲任何類型的UI(Web或窗口)提供抽象視圖。爲了做到這一點,我必須使用Interface(IView),其中我只能應用關於視圖的規則。實際上,我想設置一些基本的補充功能來提供它的繼承。要滿足要求的接口或抽象類

所以這樣我就必須使用抽象類。問題是

1)接口只有規則 2)視圖(Web表單或窗口的形式),不能承受任何更多,因爲這已經從窗口或網頁形式繼承

我怎麼能這樣做? 非常感謝

回答

5

您添加的函數是否會更改類的定義,還是僅僅創建函數來操作已經是類的一部分的數據?

如果你需要重新定義這兩個類的基類的方面,那麼是的,你將需要改變你的繼承結構。但是,如果函數只是簡單地操縱已經是類的一部分的數據,那麼我會建議你使用接口並創建實用函數。

這裏是我的意思笨拙例如:

using System; 

abstract class Pet { } 

class Dog : Pet, IPet 
{ 
    public String Name { get; set; } 
    public Int32 Age { get; set; } 
} 

class Cat : Pet, IPet 
{ 
    public String Name { get; set; } 
    public Int32 Age { get; set; } 
} 

interface IPet 
{ 
    String Name { get; set; } 
    Int32 Age { get; set; } 
} 

static class PetUtils 
{ 
    public static void Print(this IPet pet) 
    { 
     Console.WriteLine(pet.Name + " is " + pet.Age); 
    } 
} 

你的兩個UI類都以這種方式或許有關。我會想象你需要以交叉的方式做的事情可以通過像我創建的實用方法來解決。我確實創建了PetUtils.Print方法作爲擴展方法,因爲這會創建實例方法的表達幻覺。如果您不使用C#3,請從public static void Print(this IPet pet)中刪除「this」。

4

你可以繼承一個具體的類(web窗體/窗體),聲明你的類的抽象,並且仍然實現一個接口。

System.Web.UI.Page例如:

public interface IView 
{ 
    void Foo(); 
} 

public abstract class BasePage : Page, IView 
{ 
    //honor the interface 
    //but pass implementation responsibility to inheriting classes 
    public abstract void Foo(); 

    //concrete method 
    public void Bar() 
    { 
     //do concrete work 
    } 
} 

public class ConcretePage : BasePage 
{ 
    //implement Foo 
    public override void Foo() { } 
} 

這給你的界面的利益和具體的方法吧();

0

我想要做的就是這樣的事情

公衆爲MustInherit類ControllerBase(m的作爲{模型庫,新},V爲{IVIEW})

Inherits BaseController 

Dim model As M 
Dim view As V 
Public Sub New() 
    model = New M 
    view.Controller = Me 
    model.Controller = Me 
End Sub 
Public Overridable Function GetModel() As M 
    Return model 
End Function 
Public Overridable Function GetView() As V 
    Return view 
End Function 

末級

Public Class BaseWindow

Inherits System.Windows.Forms.Form 
Implements IView 
Dim c As BaseController 

Public Function GetController() As BaseController 
    Return c 
End Function 

Friend WriteOnly Property Controller() As BaseController Implements IView.Controller 
    Set(ByVal value As BaseController) 
     c = value 
    End Set 
End Property 

End Class

Public Class BaseWeb 
Inherits System.Web.UI.Page 
Implements IView 

Dim c As BaseController 

Public Function GetController() As BaseController 
    Return c 
End Function 

Friend WriteOnly Property Controller() As BaseController Implements IView.Controller 
    Set(ByVal value As BaseController) 
     c = value 
    End Set 
End Property 

末級

公共接口IVIEW

WriteOnly Property Controller() As BaseController 

結束接口