vb .net覆盖继承基类的子类方法

时间:2015-03-16 12:26:17

标签: .net vb.net inheritance

我正在尝试为特定的WPF控件(Autodesk的Ribbontextbox - 基于WPF文本框)创建一个“原型”类,其中包含它自己的commandhandler类。

RibbonTextBox旨在使用ICommand接口进行操作,而不是事件系统,这意味着它具有Commandhandler属性,我可以将命令分配给... 我的想法是创建一个基类,包括它自己的Command-Class,所以在派生类中我只需要覆盖execute方法。

mustinherit class BaseClass
      inherits RibbonTextBox
sub new()    
    me.Commandhandler= New CommandBase
end sub 

public Class CommandBase
           implements ICommand
       Protected Overridable Function CanExecute(parameter As Object) As Boolean Implements System.Windows.Input.ICommand.CanExecute
        Return Not parameter.value.ToString.IsEmptyStringOrNothing
    End Function

    Public Event CanExecuteChanged(sender As Object, e As System.EventArgs) Implements System.Windows.Input.ICommand.CanExecuteChanged

    Protected Overridable Sub Execute(parameter As Object) Implements System.Windows.Input.ICommand.Execute
'This Method should be defined in the derived Instance!!!
    End Sub

end class 

我想如何使用它:

public Class DerivedClass
            inherits BaseClass

public Overrides sub me.commandhandler.Execute() 'or some similar :-)
'here the definition of commandexecution
end sub 

end Class

任何提示都表示赞赏! 谢谢, d

2 个答案:

答案 0 :(得分:0)

您必须使用OverridableOverrides修饰符,例如here。此外,您需要确保继承的Public中的基本功能可见(ProtectedClass)。最后,您需要确保使用正确的语法:

Public Overrides Sub Execute()
'here the definition of commandexecution
End Sub 

答案 1 :(得分:0)

您可以通过这种方式覆盖其他类。如果您不想使用事件,则可以使用其他接口来接收命令。

创建CommandBase时,将类的实例作为参数传递。当CommandBase收到命令时,它将调用该实例。

MustInherit Class BaseClass
    Inherits RibbonTextBox
    Implements ICommandAction

    Sub New()
        Me.Commandhandler = New CommandBase(Me)
    End Sub

    Protected MustOverride Sub Execute(ByVal parameter As Object) Implements ICommandAction.Executecommand

End Class

Public Class CommandBase
    Implements ICommand

    Public Sub New(ByVal receiver As ICommandAction)
        _receiver = receiver
    End Sub

    Protected Overridable Function CanExecute(ByVal parameter As Object) As Boolean Implements System.Windows.Input.ICommand.CanExecute
        Return Not parameter.value.ToString.IsEmptyStringOrNothing
    End Function

    Public Event CanExecuteChanged(ByVal sender As Object, ByVal e As System.EventArgs) Implements System.Windows.Input.ICommand.CanExecuteChanged

    Protected Overridable Sub Execute(ByVal parameter As Object) Implements System.Windows.Input.ICommand.Execute
        _receiver.Executecommand(parameter)
    End Sub

End Class

Public Class DerivedClass
    Inherits BaseClass

    Protected Overrides Sub Execute(ByVal parameter As Object)

    End Sub

End Class

这是ICommandAction的样子

Interface ICommandAction

    Sub Executecommand(ByVal parameter As Object)

End Interface