我希望为任何类型的UI(Web或窗口)提供抽象视图。为了做到这一点,我必须使用Interface(IView),其中我只能应用关于视图的规则。事实上,我想设置一些基本的补充函数来提供它的继承。
所以这样,我必须使用抽象类。问题是
1)界面只有规则 2)视图(Web表单或窗口表单)不能继承,因为它已经从窗口或Web表单继承了
我该怎么做? 非常感谢
答案 0 :(得分: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,请从this
删除“public static void Print(this IPet pet)
”。
答案 1 :(得分: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() { }
}
这为您提供了界面和具体方法Bar();
的好处答案 2 :(得分:0)
我想做的是这样的事情
公共MustInherit类ControllerBase(M作为{ModelBase,New},V As {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
结束班
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
结束班
Public Interface IView
WriteOnly Property Controller() As BaseController
结束界面