VB.net 类 - 对象引用未设置为对象的实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15386198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:46:47  来源:igfitidea点击:

VB.net classes - Object reference not set to an instance of an object?

arraysvb.netclassobjectinstance

提问by Josh I

I'm working on an application in VB that is giving me some trouble. Coming from Java and C++, the class syntax for VB is peculiar. I have my main form, and a class I created called WebElement. I imported the class to MainForm.vband declared an array of WebElement's. When I try to set or get the Nameattribute of the first element of my array of 'WebElement`'s, it gives me an error - "Object reference not set to an instance of an object?"What does this mean, and how do I fix it?

我正在 VB 中开发一个应用程序,它给我带来了一些麻烦。来自 Java 和 C++,VB 的类语法很奇特。我有我的主窗体,以及我创建的一个名为WebElement. 我将类导入到MainForm.vb并声明了一个WebElement's数组。当我尝试设置或获取Name我的“WebElement”数组的第一个元素的属性时,它给了我一个错误 - “未将对象引用设置为对象的实例?” 这是什么意思,我该如何解决?

Code
MainForm.vb

代码
MainForm.vb

Imports MyProgram.WebElement

Public Class MainForm

    Private webpage(0 To 9) As WebElement
    Private pageNum As Integer = 0

    Private Sub openFile() Handles OpenToolStripMenuItem.Click
        webpage(pageNum).setName("rawr")
        MsgBox(webpage(pageNum).getName())
    End Sub

End Class


WebElement.vb

WebElement.vb

Public Class WebElement

    Private Name As String

    Public Function setName(ByRef n As String)
        Name = n
    End Function

    Public Function getName()
        Return Name
    End Function

End Class

回答by Ash Burlaczenko

You don't fill your array with WebElements, you only tell it what size it needs to be. So webpage(pageNum)is a null object.

你不用用 填充你的数组WebElements,你只告诉它它需要什么大小。webpage(pageNum)空对象也是如此。

Try

尝试

Private Sub openFile() Handles OpenToolStripMenuItem.Click
    webpage(pageNum) = New WebElement()
    webpage(pageNum).setName("rawr")
    MsgBox(webpage(pageNum).getName())
End Sub

回答by Cody Gray

The class syntax in VB.NET may be peculiar, but the usageof classes is very similar to Java and C++.

VB.NET 中的类语法可能很奇特,但类的用法与Java 和C++ 非常相似。

In particular, there is a difference between a definitionof a class type(which you've written in WebElement.vband imported into your MainForm.vbcode file), and an objectof that class type. The latter is the one that you're missing.

特别是,类类型定义(您已写入并导入到代码文件中)与该类类型的对象之间存在差异。后者是你所缺少的。WebElement.vbMainForm.vb

You need to create (instantiate) an object of the WebElementclass type in your code. The array you have declared right now is empty (i.e., all of its elements are null). All you've done is declaredit. The compiler doesn't create and fill it with objects until you ask it to do so.

您需要在代码中创建(实例化)WebElement类类型的对象。您现在声明的数组是空的(即,它的所有元素都为空)。你所做的一切都被宣布了。编译器不会创建并用对象填充它,直到您要求它这样做。

You need to initializethe elements in the array with a new object. You do this by using the Newkeyword. The syntax looks like this:

您需要使用新对象初始化数组中的元素。您可以通过使用New关键字来完成此操作。语法如下所示:

webpage(0) = New WebElement()   ' initializes the first element in the array
                                ' with a new WebElement object

You can also initialize the array elements inline when you declare it, if you so choose. In order to make this magic happen, you omit the size from the left side of the declaration and use an initializer list on the right, like so:

如果您愿意,也可以在声明时内联初始化数组元素。为了实现这个魔法,你省略了声明左侧的大小,并在右侧使用了一个初始化列表,如下所示:

Dim webpage() As WebElement = {
                               New WebElement(),
                               New WebElement(),
                               New WebElement(),
                               New WebElement(),
                               New WebElement(),
                               New WebElement(),
                               New WebElement(),
                               New WebElement(),
                               New WebElement(),
                               New WebElement()
                              }

But this syntax gets pretty unwieldy for long arrays, so most people prefer looping over the elements of the array immediately after declaration and creating the objects.

但是这种语法对于长数组来说变得非常笨拙,所以大多数人更喜欢在声明和创建对象后立即循环遍历数组的元素。

回答by Steve

This line

这条线

 Private webpage(0 To 9) As WebElement

declares an array of 10 elements that should be of type WebElement.
No element is present in the array. So every slot is Nothing (null in C#).
Calling a method on a null element will give the NullReferenceException

声明一个包含 10 个元素的数组,该数组的类型应该是 WebElement。
数组中不存在任何元素。所以每个插槽都是空的(在 C# 中为 null)。
在空元素上调用方法将给出 NullReferenceException

You should check you element before calling the method and, if it is null, create the element and assign it to the required slot

您应该在调用该方法之前检查您的元素,如果它为空,则创建该元素并将其分配给所需的插槽

Private Sub openFile() Handles OpenToolStripMenuItem.Click
    if webpage(pageNum) Is Nothing Then
       webpage(pageNum) = new WebElement()
    End If
    webpage(pageNum).setName("rawr")
    MsgBox(webpage(pageNum).getName())
End Sub

As a side note, why don't you try to use the NET syntax to implement class properties

作为旁注,为什么不尝试使用 NET 语法来实现类属性

Public Class WebElement

    Private Name As String
    Public Property Name() As String
        Get
            Return Name
        End Get
        Set(ByVal value As String)
            Name = value
        End Set
    End Property
End Class

and then use it in your code

然后在你的代码中使用它

 webpage(pageNum).Name = "rawr"
 MessageBox.Show(webpage(pageNum).Name)

回答by Zdeslav Vojkovic

You have created webpagearray, but all of its elements are null, so webpage(pageNum).setName("rawr")dereferences a null object

您已创建webpage数组,但其所有元素均为空,因此webpage(pageNum).setName("rawr")取消引用空对象

回答by Mitch Bukaner

That means NullPointerException because the objects haven′t been initialized, just like in java.

这意味着 NullPointerException 因为对象还没有被初始化,就像在 java 中一样。

try

尝试

Private webpage(0 To 9) As New WebElement

Private webpage(0 To 9) As New WebElement