성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
[정성태] 만드실 수 있습니다. 단지, Unity 엔진 내의 스크립트와 W...
[공진영] 안녕하세요 좋은글 감사합니다. 현재 제가 wpf로 관제 모...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements)</h1> <p> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# 9.0 - (1) <a target='tab' href='https://github.com/dotnet/csharplang/issues/100'>대상으로 형식화된 new 식(Target-typed new expressions)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12363'>https://www.sysnet.pe.kr/2/0/12363</a> C# 9.0 - (2) <a target='tab' href='https://github.com/dotnet/csharplang/issues/1738'>localsinit 플래그 내보내기 무시(Suppress emitting localsinit flag)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12364'>https://www.sysnet.pe.kr/2/0/12364</a> C# 9.0 - (3) <a target='tab' href='https://github.com/dotnet/csharplang/issues/111'>람다 메서드의 매개 변수 무시(Lambda discard parameters)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12365'>https://www.sysnet.pe.kr/2/0/12365</a> C# 9.0 - (4) <a target='tab' href='https://github.com/dotnet/csharplang/issues/435'>원시 크기 정수(Native ints)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12366'>https://www.sysnet.pe.kr/2/0/12366</a> C# 9.0 - (5) <a target='tab' href='https://github.com/dotnet/csharplang/issues/1888'>로컬 함수에 특성 지정 가능(Attributes on local functions)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12372'>https://www.sysnet.pe.kr/2/0/12372</a> C# 9.0 - (6) <a target='tab' href='https://github.com/dotnet/csharplang/issues/191'>함수 포인터(Function pointers)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12374'>https://www.sysnet.pe.kr/2/0/12374</a> C# 9.0 - (7) <a target='tab' href='https://github.com/dotnet/csharplang/issues/2850'>패턴 일치 개선 사항(Pattern matching enhancements)</a> ; https://www.sysnet.pe.kr/2/0/12383 C# 9.0 - (8) <a target='tab' href='https://github.com/dotnet/csharplang/issues/275'>정적 익명 함수 (static anonymous functions)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12389'>https://www.sysnet.pe.kr/2/0/12389</a> C# 9.0 - (9) <a target='tab' href='https://github.com/dotnet/csharplang/issues/39'>레코드 (Records)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12392'>https://www.sysnet.pe.kr/2/0/12392</a> C# 9.0 - (10) <a target='tab' href='https://github.com/dotnet/csharplang/issues/2460'>대상으로 형식화된 조건식(Target-typed conditional expressions)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12399'>https://www.sysnet.pe.kr/2/0/12399</a> C# 9.0 - (11) <a target='tab' href='https://github.com/dotnet/csharplang/issues/2844'>공변 반환 형식(Covariant return types)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12402'>https://www.sysnet.pe.kr/2/0/12402</a> C# 9.0 - (12) <a target='tab' href='https://github.com/dotnet/csharplang/issues/3194'>foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12403'>https://www.sysnet.pe.kr/2/0/12403</a> C# 9.0 - (13) <a target='tab' href='https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/module-initializers.md'>모듈 이니셜라이저(Module initializers)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12404'>https://www.sysnet.pe.kr/2/0/12404</a> C# 9.0 - (14) <a target='tab' href='https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/extending-partial-methods.md'>부분 메서드에 대한 새로운 기능(New features for partial methods)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12405'>https://www.sysnet.pe.kr/2/0/12405</a> C# 9.0 - (15) <a target='tab' href='https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/top-level-statements.md'>최상위 문(Top-level statements)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12406'>https://www.sysnet.pe.kr/2/0/12406</a> C# 9.0 - (16) <a target='tab' href='https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/unconstrained-type-parameter-annotations'>제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12423'>https://www.sysnet.pe.kr/2/0/12423</a> </pre> <br /> <hr style='width: 50%' /><br /> <br /> C# 7.0에 추가된 패턴 매칭이 개선을 거듭하고 있습니다. ^^ 8.0에서도 <a target='tab' href='https://learn.microsoft.com/ko-kr/dotnet/csharp/whats-new/csharp-8#switch-expressions'>switch 식</a>, <a target='tab' href='https://learn.microsoft.com/ko-kr/dotnet/csharp/whats-new/csharp-8#property-patterns'>속성 패턴</a>, <a target='tab' href='https://learn.microsoft.com/ko-kr/dotnet/csharp/whats-new/csharp-8#tuple-patterns'>튜플 패턴</a>, <a target='tab' href='https://learn.microsoft.com/ko-kr/dotnet/csharp/whats-new/csharp-8#positional-patterns'>위치 패턴</a>이 추가되더니 9.0부터 "Type Patterns", "Relational Patterns", "Pattern Combinators", "Parenthesized Patterns" 4가지가 더 구현되었습니다.<br /> <br /> 먼저 간단하게 "Type Patterns"를 살펴보면, 패턴 매칭 조건에 type 명을 직접 쓸 수 있게 되었습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > static void Main(string[] args) { // <a target='tab' href='https://github.com/dotnet/csharplang/issues/2925'>https://github.com/dotnet/csharplang/issues/2925</a> var t = (args.Length, nameof(Main)); if (<span style='color: blue; font-weight: bold'>t is (int, string)</span>) { } // test if o1 is an int and o2 is a string object objValue = args.Length; switch (objValue) { case <span style='color: blue; font-weight: bold'>int</span>: break; // test if o1 is an int case <span style='color: blue; font-weight: bold'>System.String</span>: break; // test if o1 is a string } } </pre> <br /> 참고로, C# 8.0 이전에서도 type patterns가 가능했지만 불필요한 변수 명을 기재해야만 했습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > static void Main(string[] args) { var t = (args.Length, nameof(Main)); object objValue = args.Length; { if (t is (int <span style='color: blue; font-weight: bold'>number</span>, string <span style='color: blue; font-weight: bold'>text</span>)) { } } { switch (objValue) { case int <span style='color: blue; font-weight: bold'>number</span>: break; case System.String <span style='color: blue; font-weight: bold'>text</span>: break; } } } </pre> <br /> 혹은 변수 명이 필요 없으면 생략하는 것도 가능했지만,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > if (t is (int <span style='color: blue; font-weight: bold'>_</span>, string <span style='color: blue; font-weight: bold'>_</span>)) { } switch (objValue) { case int <span style='color: blue; font-weight: bold'>_</span>: break; case System.String <span style='color: blue; font-weight: bold'>_</span>: break; } </pre> <br /> 이젠 그럴 필요도 없어진 것입니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 그다음 "Relational Patterns"의 경우 기존의 관계 연산자 중 <, <=, >, >= 4가지를 패턴 매칭에 적용한 것으로 sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, and decimal 값으로 평가되는 상수식을 대상으로만 가능합니다. 가령 다음의 코드는 가능하지만,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public static bool GreaterThan10(int number) => number is > 10; </pre> <br /> 상수 조건이 아니면 오류가 발생합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public static bool GreaterThan(int number, int target) => number is > target; // CS0150 A constant value is expected </pre> <br /> 만약 상수 제약을 벗어나고 싶다면 기존부터 가능했던 switch를 이용한 when 조건을 추가하는 식으로 처리해야 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public static bool GreaterThan(int number, int target) => number switch { int value when value > target => true, _ => false }; </pre> <br /> <hr style='width: 50%' /><br /> <br /> 마지막으로 "Pattern Combinators", "Parenthesized Patterns"를 함께 알아보겠습니다. 우선 "Pattern Combinators"의 경우, 패턴 매칭에 논리 연산 기능을 추가한 것으로 각각 "and", "or", "not"이 구현되었습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // <a target='tab' href='https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#pattern-matching-enhancements'>https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#pattern-matching-enhancements</a> public static bool IsLetter(this char c) => c is >= 'a' <span style='color: blue; font-weight: bold'>and</span> <= 'z' <span style='color: blue; font-weight: bold'>or</span> >= 'A' <span style='color: blue; font-weight: bold'>and</span> <= 'Z'; </pre> <br /> 보는 바와 같이 and, or 덕분에 단일 패턴 매칭 식을 결합 조건으로 다양하게 구성하는 것이 가능해졌습니다. 또한, 패턴 매칭의 논리 연산 기능 역시 예의 &&, ||, ! 논리 연산자와 유사하게 not, and, or 순의 우선순위가 있으므로 만약 그 우선순위를 조정해야 한다면 "Parenthesized Patterns", 즉 괄호를 이용한 제어가 가능합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public static bool IsLetterOrSeparator(this char c) => c is <span style='color: blue; font-weight: bold'>(>= 'a' and <= 'z')</span> or <span style='color: blue; font-weight: bold'>(>= 'A' and <= 'Z')</span> or '.' or ','; </pre> <br /> 물론, 위와 같은 "Pattern Combinators"를 사용하지 않고도 기존에 다음과 같은 식으로 표현하는 것이 가능했었지만,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public static bool IsLetter(char c) => c switch { char _ when c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' => true, _ => false }; public static bool IsLetterOrSeparator(char c) => c switch { char _ when (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '.' || c == ',' => true, _ => false }; </pre> <br /> C# 9.0부터는 표현이 더 간결해진 것입니다. 참고로 한 가지 더 반가운 소식이 있다면, not의 도입으로 인해 그동안 가능하지 않았던 is 패턴 구문에서의 null 부정 평가 구문을,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > if (!(objValue is null)) { Console.WriteLine("not null"); } </pre> <br /> 훨씬 더 자연스럽게 쓸 수 있게 되었습니다. ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > if (objValue is not null) { Console.WriteLine("not null"); } </pre> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1645&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
6239
(왼쪽의 숫자를 입력해야 합니다.)