Arrays VB.NET数组显式声明问题

Arrays VB.NET数组显式声明问题,arrays,vb.net,controls,scope,multidimensional-array,Arrays,Vb.net,Controls,Scope,Multidimensional Array,代码: 在这里,我在类范围中声明了两个二维数组,其中包含两个文本框的位置和大小。我很确定我遇到了这个错误: Recipe Manager.exe中发生类型为“System.InvalidOperationException”的未处理异常 其他信息:创建表单时出错。有关详细信息,请参见Exception.InnerException。错误是:对象引用未设置为对象的实例 由于位置和大小尚不存在,是否有其他方法来声明它们?因为我想我现在已经理解了您的问题,我将提供一个示例,说明如何在您的情况下初始化数

代码:

在这里,我在类范围中声明了两个二维数组,其中包含两个文本框的位置和大小。我很确定我遇到了这个错误:

Recipe Manager.exe中发生类型为“System.InvalidOperationException”的未处理异常 其他信息:创建表单时出错。有关详细信息,请参见Exception.InnerException。错误是:对象引用未设置为对象的实例


由于位置和大小尚不存在,是否有其他方法来声明它们?

因为我想我现在已经理解了您的问题,我将提供一个示例,说明如何在您的情况下初始化数组:

您希望在类中有一个全局变量,并使用其他对象的属性初始化它。要做到这一点,必须首先初始化其他对象(否则,如果您尝试使用它们,您将获得NullReferenceException)

通常最好不要内联初始化全局变量,因为您不知道每个变量在哪一点获得其值。最好使用一些初始化方法,该方法在应用程序开始时直接在您完全控制的点调用。然后可以确定变量的所有值

我编写了一些示例代码,其中还使用了
Form.Load
事件。(如果您真的想控制启动顺序,最好也禁用
应用程序框架
,并使用自定义的
子主键
作为入口点,但在这里使用
Form.Load


在初始化其他选项后,为什么不初始化阵列?以前尝试这样做没有任何意义。你想实现什么?我需要数组的作用域成为我的整个类,如果我在Form_Load事件处理程序中这样做,那么类的其余部分将无法访问它。作用域由声明而不是初始化决定。例如,如果您在类中将行
Private ingredientProperties(,)作为整数
,然后执行
ingredientProperties={{ingredient1.Location.X,ingredient1.Location.Y},{ingredient1.Size.Width,ingredient1.Size.Height}
在您的
表单\u Load
中,变量已初始化,可以按照您的需要访问它。为此,我找到了一种方法,但这一种更好:)
Private ingredientProperties(,) As Integer = {{ingredient1.Location.X, ingredient1.Location.Y}, {ingredient1.Size.Width, ingredient1.Size.Height}} ' {{ingredient location X, Y}, {ingredient size X, Y}}
Private amountProperties(,) As Integer = {{amount1.Location.X, amount1.Location.Y}, {amount1.Size.Width, amount1.Size.Height}} ' {{amount location X, Y}, {amount size X, Y}}
Public Class Form1

    'Global variables
    Private MyIngredient As Ingredient 'See: No inline initialization
    Private IngredientProperties(,) As Integer 'See: No inline initialization

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'At this stage, nothing is initialized yet, neither the ingredient, nor your array
        'First initialize the ingredient
        MyIngredient = New Ingredient

        'Now you can enter the values into the array
        With MyIngredient 'Make it more readable
            IngredientProperties = {{.Location.X, .Location.Y}, _
                                    {.Size.Width, .Size.Height}}
        End With
    End Sub
End Class

Public Class Ingredient
    Public Location As Point
    Public Size As Size
    Public Sub New()
        'Example values
        Location = New Point(32, 54)
        Size = New Size(64, 64)
    End Sub
End Class