null 개체를 참조하여 발생하는 오류를 처리합니다. Null 참조 예외는 null을 가리키는 멤버 필드 또는 함수 유형에 액세스하려고 할 때 발생합니다.
다음 null 문자열이 있다고 가정해 보겠습니다. -
string str = null;
이제 널 문자열의 길이를 얻으려고 하면 예외가 발생합니다 -
If(str.Length == null) {} 위의 예외가 throw됩니다. 이제 null 포인터 예외가 throw되는 것을 방지하는 방법을 살펴보겠습니다. -
예시
using System;
class Program {
static void Main() {
int[] arr = new int[5] {1,2,3,4,5};
display(arr);
arr = null;
display(arr);
}
static void display(int[] arr) {
if (arr == null) {
return;
}
Console.WriteLine(arr.Rank);
}
} 출력
1