vb .net 覆盖继承基础 class 的 subclass 方法

vb .net override subclass method of inherited base class

我正在尝试为特定的 WPF 控件(Autodesk 的 Ribbontextbox - 基于 WPF 文本框)创建一个 "prototype" class,其中包括它自己的命令处理程序 class。

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

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

您必须使用 OverridableOverrides 修饰符,例如 here。此外,您需要确保基函数在继承的 Class 中可见(PublicProtected)。最后,您需要确保使用正确的语法:

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

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

创建 CommandBase 时,您将 class 的实例作为参数传递。当 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