采用泛型的模式匹配pattern-matching with generics
- [x] 建议[x] Proposed
- [] 原型:[ ] Prototype:
- [] 实现:[ ] Implementation:
- [] 规范:[ ] Specification:
总结Summary
现有 c # as 运算符的规范允许在操作数的类型与指定类型之间不进行任何转换。The specification for the existing C# as operator permits there to be no conversion between the type of the operand and the specified type when either is an open type. 但是,在 c # 7 中,该 Type identifier
模式要求输入类型与给定类型之间存在转换。However, in C# 7 the Type identifier
pattern requires there be a conversion between the type of the input and the given type.
我们建议放宽此项更改 expression is Type identifier
,并在 c # 7 中允许的条件下允许这样做,但允许时也允许这样做 expression as Type
。We propose to relax this and change expression is Type identifier
, in addition to being permitted in the conditions when it is permitted in C# 7, to also be permitted when expression as Type
would be allowed. 具体而言,这种情况下,表达式或指定类型的类型是开放类型。Specifically, the new cases are cases where the type of the expression or the specified type is an open type.
动机Motivation
当前允许模式匹配 "明显" 的情况当前无法编译。Cases where pattern-matching should "obviously" be permitted currently fail to compile. 有关示例,请参阅 https://github.com/dotnet/roslyn/issues/16195 。See, for example, https://github.com/dotnet/roslyn/issues/16195.
详细设计Detailed design
我们更改了模式匹配规范中的段落 (建议的添加项以粗体显示) :We change the paragraph in the pattern-matching specification (the proposed addition is shown in bold):
左侧和给定类型的静态类型的某些组合被视为不兼容并导致编译时错误。Certain combinations of static type of the left-hand-side and the given type are considered incompatible and result in compile-time error.
E
T
如果存在标识转换、隐式引用转换、装箱转换、显式引用转换或从到的取消装箱转换,E
T
或者E
或T
是开放类型, 则将静态类型的值称为模式与类型兼容。A value of static typeE
is said to be pattern compatible with the typeT
if there exists an identity conversion, an implicit reference conversion, a boxing conversion, an explicit reference conversion, or an unboxing conversion fromE
toT
, or if eitherE
orT
is an open type. 如果类型为的表达式E
与类型模式中的类型不兼容,则这是编译时错误。It is a compile-time error if an expression of typeE
is not pattern compatible with the type in a type pattern that it is matched with.
缺点Drawbacks
无。None.
备选方法Alternatives
无。None.
未解决的问题Unresolved questions
无。None.
设计会议Design meetings
LDM 认为这是一个问题,认为这是一个 bug 修复级别的更改。LDM considered this question and felt it was a bug-fix level change. 我们将其视为一种独立的语言功能,因为只要在语言发布后进行更改,就会引入不兼容性。We are treating it as a separate language feature because just making the change after the language has been released would introduce a forward incompatibility. 使用建议的更改需要程序员指定语言版本7.1。Using the proposed change requires that the programmer specify language version 7.1.