How to handle a class you want to extend which is sealed in the .NET library?

前端 未结 7 1434
礼貌的吻别
礼貌的吻别 2021-01-02 02:54

I was reading somewhere about how to handle the issue of wanting to extend a sealed class in the .NET Framework library.

This is often a common and useful task to do

7条回答
  •  执笔经年
    2021-01-02 03:30

    this method may have already been mentioned above by it's formal name, but i don't know it's formal name, so here it is. This example "extends" the TextBox class (example in VB). I believe an advantage of this method is that you do not need to explicitly code or expose built-in members. Hope this is relevant:

    VB Class Module "MyTextBox":

    public Base as TextBox, CustomProperty as Integer
    
    Private Sub Init(newTextBox as TextBox)
        Set Base = newTextBox
    End Sub
    
    public Property Get CustomProperty2() As String
        CustomProperty2 = "Something special"
    End Property
    

    To call the code, you might say:

    Dim MyBox as New MyTextBox
    MyBox.Init MyForm.TextBox3
    

    from here you have access to all built-in members, plus your custom members.

    Debug.Print MyBox.Base.Text
    MyBox.CustomProperty = 44
    

    For extra polish, you can make Base the default property of the class, and then you can leave out "Base" when you call properties of the Base class. You call Base members like this:

    Debug.Print MyBox().Text
    MyBox().Text = "Hello World"
    

    VBA Demo

提交回复
热议问题