>  기사  >  백엔드 개발  >  C#에서는 null 값을 처리하기 위해 어떤 연산자를 제공합니까?

C#에서는 null 값을 처리하기 위해 어떤 연산자를 제공합니까?

WBOY
WBOY앞으로
2023-09-23 17:57:021094검색

C# 提供哪些运算符来处理空值?

C#에는 null 값을 처리하는 다음 세 가지 연산자가 있습니다. -

Null 병합 연산자(??)

를 사용하면 null이 아닌 변수의 값을 가져오거나 null이 아닌 기본값을 지정할 수 있습니다. 사용됩니다.

C#의 -

string resultOne = value != null ? value : "default_value";

표현식을 -

string resultTwo = value ?? "default_value";

표현식으로 대체합니다. 다음은 이를 설명하는 예입니다.

using System;
class Program{
   static void Main(){
      string input = null;
      string choice = input ?? "default_choice";
      Console.WriteLine(choice); // default_choice
      string finalChoice = choice ?? "not_chosen";
      Console.WriteLine(finalChoice); // default_choice
   }
}

Null 병합 할당 연산자(??=)

null이 아닌 경우 왼쪽 값을 반환합니다. 그렇지 않으면 오른쪽 값을 반환합니다. 즉, 현재 값이 null인 경우 변수를 일부 기본값으로 초기화할 수 있습니다.

C#에서 다음 표현식을 대체합니다. -

if (result == null)
result = "default_value";

다음 표현식을 사용하세요.

result ??= "default_value";

이 연산자는 지연 계산 속성에 유용합니다. 예를 들어 -

Example

class Tax{
   private Report _lengthyReport;
   public Report LengthyReport => _lengthyReport ??= CalculateLengthyReport();
   private Report CalculateLengthyReport(){
      return new Report();
   }
}

Null 조건 연산자(?.)

이 연산자를 사용하면 인스턴스에서 메서드를 안전하게 호출할 수 있습니다. 인스턴스가 null인 경우 NullReferenceException을 발생시키는 대신 null을 반환합니다. 그렇지 않으면 메서드를 호출하기만 합니다.

C#의 -

string result = instance == null ? null : instance.Method();

표현식을 -

string result = instance?.Method();

표현식으로 대체합니다. 다음 예를 살펴보세요.

Example

using System;
string input = null;
string result = input?.ToString();
Console.WriteLine(result); // prints nothing (null)

Example

실시간 시연

using System;
class Program{
   static void Main(){
      string input = null;
      string choice = input ?? "default_choice";
      Console.WriteLine(choice); // default_choice
      string finalChoice = choice ?? "not_chosen";
      Console.WriteLine(finalChoice); // default_choice
      string foo = null;
      string answer = foo?.ToString();
      Console.WriteLine(answer); // prints nothing (null)
   }
}

Output

default_choice
default_choice

위 내용은 C#에서는 null 값을 처리하기 위해 어떤 연산자를 제공합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제
이전 기사:C#의 반복 기술다음 기사:C#의 반복 기술