>  기사  >  백엔드 개발  >  C# NullReferenceException

C# NullReferenceException

WBOY
WBOY원래의
2024-09-03 15:21:04899검색

NullReferenceException은 값이 null인 모든 유형의 멤버에 액세스하려고 할 때 프로그램에서 발생하는 예외입니다. 즉, 값이 없거나 null 값을 보유하지 않는 변수에 액세스하려고 하면 Null 참조 예외가 발생합니다. 던져진다. 이 예외는 .NET, .NET Core 및 .Net Framework의 다양한 릴리스에 적용됩니다. C#의 이러한 참조 변수는 C의 pf 포인터 개념과 상당히 일치합니다. NullReferenceException이 발생하는 상황은 다양하며 이를 방지하거나 해결하는 방법은 여러 가지가 있습니다.

구문:

다음은 NullReferenceException 구현에 사용되는 표준 구문입니다.

public class NullReferenceException :SystemException

Null 참조 예외는 기본적으로 Object 및 Exception에서 찾을 수 있는 시스템 예외에서 상속됩니다. 아시다시피 이는 가장 일반적인 예외 중 하나이며 이를 처리하는 방법은 다양합니다.

C#에서 NullReferenceException은 어떻게 작동하나요?

간단히 이해하자면 Null 참조 예외는 다른 객체를 참조하지 않는 변수에 액세스하려고 시도하는 이벤트의 결과입니다. 여기서는 참조를 참조하는 것이 문제가 되지 않지만, 참조 변수가 다른 개체를 참조하지 않는 경우 기본적으로 null로 처리됩니다. 코드가 null로 끝나는 지점을 참조할 때 문제가 발생하는 경우 NullReferenceException이라는 예외가 발생합니다. 프로그램에서 Null 참조 예외가 발생하는 다양한 시나리오가 있을 수 있습니다. 프로그램을 실행할 때 null 참조 예외가 발생하면 출력은 다음과 같습니다.

처리되지 않은 예외:
System.NullReferenceException: 개체 참조가 개체의 인스턴스로 설정되지 않았습니다.

이제 예외가 무엇인지, 어떻게 작동하는지 이해했으므로 예제를 통해 예외를 올바르게 시연해 보겠습니다. 매우 간단한 첫 번째 예에서는 null 값을 보유하는 간단한 변수가 있고 해당 변수를 수행하려고 시도하지만 null이므로 Null 참조 예외가 발생합니다. 프로그램 코드는 다음과 같습니다.

코드:

using System;
public class SampleProgram {
public static void Main()     {
string name = null;
varval =name.ToString();
Console.WriteLine(val);
}
}

코드 설명: System을 사용한다고 명시하면 공개된 Sample 클래스가 있습니다. 그런 다음 정적 void main 문이 있고 이름이라는 간단한 문자열 변수가 생성되고 할당된 값은 null입니다. 이는 변수에 값이 없음을 의미합니다. 여기서는 이 문자열 변수가 중요합니다. 나중에 val이라는 다른 변수를 만들어 name 값을 문자열로 변환하려고 합니다. 마지막으로, 이제 ToString()을 사용하여 변환된 name 값을 인쇄하는 print 문이 있습니다. 출력은 아래 첨부된 스크린샷을 참조하세요.

출력:

C# NullReferenceException

제대로 실행되면 코드에서 NullReferenceException 오류가 발생합니다. 그 이유는 ToString() 메서드를 호출하려고 하면 변수 이름으로 이동하지만 변수 이름에는 값이 없으므로 null을 의미합니다. 그리고 우리가 알고 있듯이 null 값은 ToString()을 사용하여 변환할 수 없습니다. 따라서 우리 코드는 오류만 인쇄합니다. 이는 코드가 예상대로 실행되고 있음을 의미합니다.

설명드린 바와 같이 예외로 인해 프로그램이 종료되었습니다. 계속해서 설명된 대로 동일한 예외가 발생하는 또 다른 간단한 예를 보여드리겠습니다.

코드:

using System;
class SampleProgram {
static void Main() {
string val = null;
if (val.Length == 0) {
Console.WriteLine(val);
}
}
}

코드 설명: 첫 번째 예와 유사하게 여기에는 기본 문을 포함하는 네임스페이스와 첫 번째 호출이 있습니다. 그런 다음 값이 null인 문자열 변수가 있습니다. 이는 예상되는 예외로 이어지는 주요 변수가 됩니다. 그런 다음 변수의 길이가 0인지 아닌지 확인하고 0이면 다음 단계로 이동하여 값을 인쇄하는 간단한 if 조건이 있습니다. 그러나 코드는 if 내에서 예외가 발생하므로 최종 인쇄 줄로 이동하지 않습니다. 출력은 아래 첨부된 스크린샷을 참조하세요.

출력:

C# NullReferenceException

여기서 출력은 첫 번째 예인 "처리되지 않은 예외"와 같습니다. 예외가 동일하기 때문에 여기에서 함수를 구현하려고 시도했지만 설명된 대로 변수에 Null 참조 예외가 발생하는 null 값이 있습니다. 이제 이 null 참조 예외가 발생하는 방법과 이유를 살펴보고 이해했으므로 프로그램의 더 나은 기능을 위해 이를 방지할 수 있는 방법을 이해하는 것이 중요합니다.

How to Avoid NullReferenceException in C#?

The Null Reference Exception is not a major error, but one of the common ones and one of the basic and simple way to avoid the Null Reference Exception is to check the variable or property before moving ahead and accessing it. And a very basic way to do this is to check the variable within an if statement. We will demonstrate an example where we will avoid the occurrence of the exception and the code will move on.

Code:

using System;
class SampleProgram {
static void Main() {
string val = null;
if (val == null) {
Console.WriteLine("\n Value to the variable is null.");
}
else{
Console.WriteLine(val);
}
}
}

Output:

C# NullReferenceException

Code Explanation: Here we have our class which holds the main statement than a variable with a null value. Then we enter an if else statement, where the value of the variable is checked if it is null, the print statement will be printed and the program will terminate, if the value is not null, then it will move ahead and into else part, it will print the value. As expected our code printed that “Value to the variable is null.” because the value is null. If we try the same example with a string value, the program will proceed and the else part will be printed.

Conclusion

The NullReferenceException is encountered when we attempt to access a variable which holds a null value, it can be variable or object. The reference should not hold null value else the exception will be thrown. There are many situations where this can be seen and the simplest way to avoid the NullReferenceException is to check beforehand, before accessing the value.

위 내용은 C# NullReferenceException의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:C# FileNotFoundException다음 기사:C# FileNotFoundException