2014-07-20 7 views
0

CODE : 여기VB.NET 배열 명시 적으로 선언 문제

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

내가 두 개의 2 차원 배열의 위치와 두 개의 텍스트 상자의 크기를 포함하는 클래스의 범위를 선언하고있다. 이 오류가 발생하는 것이 확실합니다.

An unhandled exception of type 'System.InvalidOperationException' occurred in Recipe Manager.exe Additional information: An error occurred creating the form. See Exception.InnerException for details. The error is: Object reference not set to an instance of an object.

위치 및 크기가 아직 존재하지 않으므로 선언 할 수있는 다른 방법이 있습니까?

+1

왜하지 다른 옵션이 초기화 된 후에 배열을 초기화합니까? 이전에 해보고 시도하는 것은 의미가 없습니다. 무엇을 성취하려고합니까? – Jens

+0

배열의 범위가 내 전체 클래스가되어야합니다. ** Form_Load ** 이벤트 처리기에서 수행하는 경우 나머지 클래스에서 액세스 할 수 없습니다. – ohSkittle

+2

범위는 선언에 의해 결정되며 초기화. 예 : 클래스에 'Private ingredientProperties (,) As Integer'라는 줄이 있다면'ingredientsProperties = {{ingredients1.Location.X, ingredients1.Location.Y}, {ingredients1.Size.Width, ingredient1.Size. Height}}''Form_Load'에서 변수가 초기화되고 원하는대로 액세스 할 수 있습니다. – Jens

답변

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 
+0

고마워, 나는이 방법이 더 낫다는 것을 알았다. :) – ohSkittle

관련 문제