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

所以我创建了一个继承自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

我在Google上搜索过,有人说需要覆盖 CreateControlsInstance 方法。所以我这样做了,但它给 InvalidOperationException 带了 NullReferenceException innerException 消息。

我该如何实现?

有帮助吗?

解决方案

为什么不继承 UserControl 定义具有Text和Image等属性的自定义控件?

其他提示

最好不要只使用通用集合。 Bieng Control Collection并没有真正为它做任何特别的事。

puclic class MyCollection : Collection<Control>

如果您继承自Control.ControlCollection,则需要在类中提供New方法。您的New方法必须调用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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top