수색…


NullReferenceException 설명

NullReferenceException 은 참조 객체의 비 정적 멤버 (속성, 메서드, 필드 또는 이벤트)에 액세스하려고 시도하지만 null입니다.

Car myFirstCar = new Car();
Car mySecondCar = null;
Color myFirstColor = myFirstCar.Color; // No problem as myFirstCar exists / is not null
Color mySecondColor = mySecondCar.Color; // Throws a NullReferenceException 
// as mySecondCar is null and yet we try to access its color.

이러한 예외를 디버그하려면 매우 쉽습니다. 예외가 발생하는 행에는 모든 것을 살펴야 . '또는' [ ', 또는 드물 긴하지만' ( '.

myGarage.CarCollection[currentIndex.Value].Color = theCarInTheStreet.Color;

내 예외는 어디에서 발생합니까? 어느 한 쪽:

  • myGaragenull
  • myGarage.CarCollectionnull
  • currentIndexnull
  • myGarage.CarCollection[currentIndex.Value]null
  • theCarInTheStreetnull

디버그 모드에서는 이러한 모든 요소에 마우스 커서를 놓으면 null 참조를 찾을 수 있습니다. 그렇다면 가치가없는 이유를 이해해야합니다. 수정은 전적으로 메소드의 목표에 달려 있습니다.

인스턴스화 / 초기화하는 것을 잊었습니까?

myGarage.CarCollection = new Car[10];

객체가 null 인 경우 다른 작업을 수행해야합니까?

if (myGarage == null)
{
    Console.WriteLine("Maybe you should buy a garage first!");
}

아니면 누군가가 당신에게 널 인수를했고, 다음과 같이하지 않아도 될지도 모릅니다.

if (theCarInTheStreet == null)
{
    throw new ArgumentNullException("theCarInTheStreet");
}

어쨌든 메서드는 절대로 NullReferenceException을 던져서는 안됩니다. 만약 그렇다면, 당신이 뭔가를 확인하는 것을 잊었음을 의미합니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow