2013-04-18 3 views
1

나는 프로그램의 다른 클래스 인 Car 유형의 배열 인 속성을 갖는 Garage 클래스를 가지고 있습니다. 몇 번의 반복을 시도하고 대부분의 런타임 오류가 발생합니다. 나는 그것을 실행할 때마다 NullRefernceException을 얻습니다. 이것은 CarLot 배열의 길이 속성에 액세스하려고 시도하는 클래스 Program에서 발생합니다.생성자에서 클래스 배열 초기화

나는 대신에 배열이 클래스 인 CarLot 속성과 관련이 있다는 것을 알고 있습니다. 내가 배열을 null로 설정할 수 있도록 프로그램을 사용하려고 할 때 어떤 조각이 누락 되었습니까?

class Program 
{ 
    static void Main(string[] args) 
    { 
     Garage g = new Garage(); 
     //this is where the exception occurs 
     g.CarLot[0] = new Car(5, "car model"); 
     Console.ReadLine(); 
    } 
} 

public class Garage 
{ 
    public Car[] CarLot { get; set; } 
    public Garage() { } 
    //this should be able to be 0 or greater 
    public Garage(params Car[] c) 
    { 
     Car[] cars = { }; 
     CarLot = cars; 
    } 
} 

public class Car 
{ 
    public int VIN { get; set; } 
    public int Year { get; set; } 
    public string Model { get; set; } 
    public Car(int _vin, string _model) 
    { 
     _vin = VIN; 
     _model = Model; 
    } 
    public Car() { } 
    public void Print() 
    { 
     Console.WriteLine("Here is some information about the car {0} and {1} "); 
    } 
} 
+0

정확한 예외는 무엇입니까? –

+0

'NullReferenceException'은'g.CarLot ..' 프로그램 클래스에 있습니다 – wootscootinboogie

답변

2

배열에 자동 속성을 사용하는 대신 매개 변수없는 생성자가 Main에서 호출 될 때 개인 변수를 사용하여 배열을 초기화 할 수 있습니다.

private Car[] carLot = new Car[size]; 
public Car[] CarLot 
{ 
    get { return carLot; } 
    set { carLot = value; } 
} 

또는 매개 변수가없는 Garage 생성자에서는 그 시점에서 배열을 초기화 할 수 있습니다.

어느 쪽이든, 값을 할당하기 전에 배열을 인스턴스화해야합니다. http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

+0

그건 내 생각에 생각합니다. 나는 그 안에 아무것도 넣지 않을 길을 찾으려고 노력했다. – wootscootinboogie

+0

쿨, 기꺼이 도움 :). –

+0

내가 틀렸다면 엠메 정확하게해라. 그러나 배열'new car [SIZE]'의 크기를 지정할 필요가 없니? 이것이 컴파일 될지 확실하지 않습니다. –

1

나는 이것이 당신이 요구하는 정확한 것이 아니라는 것을 알고 있습니다. 훨씬 쉽지 않을까요?

static void Main(string[] args) 
    { 
     var garage = new List<Car>(); 
     //this is where the exception occurs 
     garage.Add(new Car(5, "car model")); 
    } 

    public class Car 
    { 
     public int VIN { get; set; } 
     public int Year { get; set; } 
     public string Model { get; set; } 
     public Car(int _vin, string _model) 
     { 
      _vin = VIN; 
      _model = Model; 
     } 
     public Car() { } 
     public void Print() 
     { 
      Console.WriteLine("Here is some information about the car {0} and {1} "); 
     } 

    } 
관련 문제