在VB.NET中扩展ControlCollection

在VB.NET中扩展ControlCollection,vb.net,inheritance,overriding,Vb.net,Inheritance,Overriding,我想在VB.NET中扩展基本的控件集合,这样我就可以将图像和文本添加到自制的控件中,然后自动将它们转换为图片框和标签 因此,我创建了一个继承自ControlCollection的类,重写了add方法,并添加了功能 但是当我运行这个示例时,它给出了一个NullReferenceException 代码如下: Shadows Sub add(ByVal text As String) Dim LB As New Label LB.Aut

我想在VB.NET中扩展基本的
控件集合
,这样我就可以将图像和文本添加到自制的控件中,然后自动将它们转换为图片框和标签

因此,我创建了一个继承自ControlCollection的类,重写了add方法,并添加了功能

但是当我运行这个示例时,它给出了一个
NullReferenceException

代码如下:

        Shadows Sub add(ByVal text As String)
            Dim LB As New Label
            LB.AutoSize = True
            LB.Text = text
            MyBase.Add(LB) 'Here it gives the exception.
        End Sub
我在谷歌上搜索,有人说需要重写
CreateControlsInstance
方法。所以我这样做了,但是它给出了
invalidooperationexception
,带有
innerException
消息
NullReferenceException


如何实现这一点?

为什么不从继承定义具有文本和图像等属性的自定义控件?

为什么不从继承定义具有文本和图像等属性的自定义控件?

无论如何,您最好只使用泛型集合。Bieng控件集合实际上并没有为它做任何特殊的事情

puclic class MyCollection : Collection<Control>
puclic类MyCollection:集合

无论如何,您最好只使用一个通用集合。Bieng控件集合实际上并没有为它做任何特殊的事情

puclic class MyCollection : Collection<Control>
puclic类MyCollection:集合

如果从Control.ControlCollection继承,则需要在类中提供新方法。新方法必须调用ControlCollection的构造函数(MyBase.New)并向其传递有效的父控件

如果没有正确执行此操作,则会在Add方法中抛出NullReferenceException

这也可能导致CreateControlsInstance方法中出现InvalidOperationException

以下代码错误地调用构造函数,导致Add方法引发NullReferenceException

Public Class MyControlCollection
    Inherits Control.ControlCollection

    Sub New()
        'Bad - you need to pass a valid control instance
        'to the constructor
        MyBase.New(Nothing)
    End Sub

    Public Shadows Sub Add(ByVal text As String)
        Dim LB As New Label()
        LB.AutoSize = True
        LB.Text = text
        'The next line will throw a NullReferenceException
        MyBase.Add(LB)
    End Sub
End Class

如果您是从Control.ControlCollection继承的,则需要在类中提供一个新方法。新方法必须调用ControlCollection的构造函数(MyBase.New)并向其传递有效的父控件

如果没有正确执行此操作,则会在Add方法中抛出NullReferenceException

这也可能导致CreateControlsInstance方法中出现InvalidOperationException

以下代码错误地调用构造函数,导致Add方法引发NullReferenceException

Public Class MyControlCollection
    Inherits Control.ControlCollection

    Sub New()
        'Bad - you need to pass a valid control instance
        'to the constructor
        MyBase.New(Nothing)
    End Sub

    Public Shadows Sub Add(ByVal text As String)
        Dim LB As New Label()
        LB.AutoSize = True
        LB.Text = text
        'The next line will throw a NullReferenceException
        MyBase.Add(LB)
    End Sub
End Class