>  기사  >  백엔드 개발  >  C# 패턴 일치

C# 패턴 일치

PHPz
PHPz원래의
2024-09-03 15:32:47405검색

데이터나 개체를 일치시키는 데 사용되는 C#의 기능을 패턴 일치라고 하며 이 패턴 일치는 is 표현식과 스위치 문을 사용하여 수행됩니다. 여기서 is 표현식은 데이터나 개체가 지정된 유형과 호환되는지 확인합니다. not 및 switch 문은 C#의 다양한 패턴을 일치시키는 데 사용됩니다. C#에서 패턴 일치를 위해 표현식 is 및 switch 문을 사용하면 애플리케이션 작성 방식을 더 읽기 쉽고, 유지 관리하기 쉽고, 이해하기 쉬운 방식으로 변경할 수 있습니다.

C# 패턴 매칭 방법

C#에는 두 가지 패턴 일치 방법이 있습니다. 그들은:

1. 표현입니다

is 표현식은 지정된 유형과 데이터 또는 객체의 호환성을 확인하는 데 사용됩니다.

예시 #1

시연할 C# 프로그램은 프로그램의 표현식입니다.

코드:

using System;
//a namespace called program is defined
namespace program
{
//a class called subject is defined in which a subject is assigned to a string variable
class Subject
{
public string SubName{ get; set; } = "C Sharp";
}
//a class called check is defined
class check
{
//main method is called
public static void Main(string[] args)
{
//an instance of the subject class is created
Subject sub = new Subject();
//is expression is used to check if the instance of the subject class is compatible with the type of the value assigned to the string variable in subject class
if(sub is Subject)
{
Console.WriteLine(sub.SubName);
}
}
}
}

출력:

C# 패턴 일치

설명: 위 프로그램에는 program이라는 네임스페이스가 정의되어 있습니다. 그런 다음 주체 이름이 문자열 변수에 할당되는 Subject라는 클래스가 정의됩니다. 그런 다음 메인 메소드가 호출되는 check라는 클래스가 정의됩니다. 그런 다음 주제 클래스의 인스턴스가 생성됩니다. 그런 다음 is 표현식을 사용하여 새로 생성된 주제 클래스의 인스턴스가 클래스 주제의 문자열 변수에 할당된 값의 유형과 호환되는지 확인합니다. 호환되는 경우 주체 이름이 출력으로 표시됩니다. 프로그램의 출력은 위의 스냅샷에 표시됩니다.

예시 #2

시연할 C# 프로그램은 Expression in a Program입니다.

코드:

using System;
//a namespace called program is defined
namespace program
{
//a class called Writer is defined in which a name of the writer is assigned to a string variable
class Writer
{
public string WriterName{ get; set; } = "ShobhaShivakumar";
}
//a class called check is defined
class check
{
//main method is called
public static void Main(string[] args)
{
//an instance of the Writer class is created
Writer write = new Writer();
//is expression is used to check if the instance of the Writer class is compatible with the type of the value assigned to the string variable in Writer class
if(write is Writer)
{
Console.WriteLine(write.WriterName);
}
}
}
}

출력:

C# 패턴 일치

설명: 위 프로그램에는 program이라는 네임스페이스가 정의되어 있습니다. 그런 다음 작성자의 이름이 문자열 변수에 할당되는 Writer라는 클래스가 정의됩니다. 그런 다음 메인 메소드가 호출되는 check라는 클래스가 정의됩니다. 그런 다음 Writer 클래스의 인스턴스가 생성됩니다. 그런 다음 is 표현식을 사용하여 Writer 클래스의 새로 생성된 인스턴스가 Writer 클래스의 문자열 변수에 할당된 값의 유형과 호환되는지 확인합니다. 호환되는 경우 작성자 이름이 출력으로 표시됩니다. 프로그램의 출력은 위의 스냅샷에 표시됩니다.

2. 스위치 설명

switch 문은 C#에서 다양한 패턴을 일치시키는 데 사용됩니다.

예시 #1

프로그램에서 Switch 문을 시연하는 C# 프로그램

코드:

using System;
//a class called check is defined
class check
{
//main method is called
public static void Main()
{
//a name is assigned to a string variable
string val = "Shobha_Shivakumar";
//switch statement is used to switch between the values that is assigned to the string variable and anything else
switch (val)
{
case "Shobha_Shivakumar":
Console.WriteLine("The assigned value is Shobha_Shivakumar");
break;
case "not_assigned":
Console.WriteLine("The assigned value is not_assigned");
break;
}
}
}

출력:

C# 패턴 일치

설명: 위 프로그램에는 check라는 클래스가 정의되어 있습니다. 그런 다음 문자열 변수에 이름이 할당되는 기본 메서드가 호출됩니다. 그런 다음 switch 문을 사용하여 문자열 변수에 할당된 값과 다른 값 사이를 전환합니다. 문자열 변수에 할당된 이름이 스위치 케이스인 경우 해당 출력이 표시됩니다. 마찬가지로 다른 것이 있으면 해당 출력이 표시됩니다. 프로그램의 출력은 위의 스냅샷과 같습니다.

예시 #2

프로그램에서 Switch 문을 보여주기 위한 C# 프로그램:

코드:

using System;
//a class check is defined
class Check
{
//main method is called
static void Main()
{
while(true)
{
Console.WriteLine("Type any alphabet between A and Z");
try
{
//a string is expected as the input by the user
string r = Console.ReadLine();
//switch statement is used to parse the input given by the user and display the output accordingly
switch(r)
{
case "A":
{
Console.WriteLine("This is Alphabet A");
break;
}
case "B":
{
Console.WriteLine("This is alphabet B");
break;
}
default:
{
Console.WriteLine("This is something other than Alphabets A and B");
break;
}
}
}
catch
{
}
}
}
}

출력:

C# 패턴 일치

설명: 위 프로그램에는 check라는 클래스가 정의되어 있습니다. 그런 다음 알파벳 A부터 Z까지의 문자열이 사용자의 입력으로 예상되는 기본 메서드가 호출됩니다. 그런 다음 switch 문을 사용하여 사용자가 제공한 입력을 구문 분석하고 그에 따라 출력을 표시합니다. 입력이 A와 B 이외의 알파벳이면 출력에도 동일하게 표시됩니다. 위 프로그램의 출력은 위의 스냅샷에 나와 있습니다.

결론

이 튜토리얼에서는 예제와 출력을 통해 패턴 일치의 정의와 방법을 통해 C#의 패턴 일치 개념을 이해합니다.

추천기사

C# 패턴 매칭에 대한 안내입니다. 여기에서는 C# 패턴 일치 소개와 해당 방법, 예제 및 코드 구현에 대해 설명합니다. 더 자세히 알아보려면 다른 추천 기사를 살펴보세요. –

  1. C#의 난수 생성기
  2. Java의 정적 생성자
  3. C#의 TextWriter
  4. C#의 정적 생성자

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

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