【问题标题】:VB.NET Array explicit declaration issueVB.NET 数组显式声明问题
【发布时间】:2014-07-20 20:03:00
【问题描述】:

代码:

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}}

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

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

因为位置和大小还不存在,有没有其他的方法来声明它们?

【问题讨论】:

  • 其他选项初始化后为什么不初始化数组呢?以前尝试这样做没有任何意义。你想完成什么?
  • 我需要将数组的范围作为我的整个班级,如果我在 Form_Load 事件处理程序中这样做,那么班级的其余部分将无法访问它跨度>
  • 范围由声明决定,而不是由初始化决定。例如。如果您的班级中只有Private ingredientProperties(,) As Integer 行,然后在您的Form_Load 中执行ingredientProperties = {{ingredient1.Location.X, ingredient1.Location.Y}, {ingredient1.Size.Width, ingredient1.Size.Height}},则该变量已初始化,并且可以按照您的需要访问它。

标签: arrays vb.net controls scope multidimensional-array


【解决方案1】:

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

您希望类中有一个全局变量,并使用其他对象的属性对其进行初始化。为此,必须先初始化其他对象(否则,如果您尝试使用它们,则会收到 NullReferenceException)。

通常最好不要内联初始化全局变量,因为你并不真正知道每个变量在什么时候得到它的值。最好使用一些在您完全控制的应用程序开始时直接调用的初始化方法。然后你就可以确定你的变量的所有值了。

我编写了一些示例代码,也使用了Form.Load 事件。 (如果您真的想控制启动顺序,最好也禁用Application Framework 并使用自定义Sub Main 作为入口点,但在这里使用Form.Load 就可以了。)

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

【讨论】:

  • 谢谢你,我想出了一个办法,但这个更好:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
  • 1970-01-01
  • 1970-01-01
  • 2014-07-12
相关资源
最近更新 更多