Extended property patterns
Note
This article is a feature specification. The specification serves as the design document for the feature. It includes proposed specification changes, along with information needed during the design and development of the feature. These articles are published until the proposed spec changes are finalized and incorporated in the current ECMA specification.
There may be some discrepancies between the feature specification and the completed implementation. Those differences are captured in the pertinent language design meeting (LDM) notes.
You can learn more about the process for adopting feature speclets into the C# language standard in the article on the specifications.
Summary
Allow property subpatterns to reference nested members, for instance:
if (e is MethodCallExpression { Method.Name: "MethodName" })
Instead of:
if (e is MethodCallExpression { Method: { Name: "MethodName" } })
Motivation
When you want to match a child property, nesting another recursive pattern adds too much noise which will hurt readability with no real advantage.
Detailed design
The property_pattern syntax is modified as follow:
property_pattern
: type? property_pattern_clause simple_designation?
;
property_pattern_clause
: '{' (subpattern (',' subpattern)* ','?)? '}'
;
subpattern
- : identifier ':' pattern
+ : subpattern_name ':' pattern
;
+subpattern_name
+ : identifier
+ | subpattern_name '.' identifier
+ ;
The receiver for each name lookup is the type of the previous member T0, starting from the input type of the property_pattern. if T is a nullable type, T0 is its underlying type, otherwise T0 is equal to T.
For example, a pattern of the form { Prop1.Prop2: pattern }
is exactly equivalent to { Prop1: { Prop2: pattern } }
.
Note that this will include the null check when T is a nullable value type or a reference type. This null check means that the nested properties available will be the properties of T0, not of T.
Repeated member paths are allowed. The compilation of pattern matching can take advantage of common parts of patterns.
C# feature specifications
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기