Why is some ordering enforced in generic parameter constraints?

后端 未结 2 734
孤城傲影
孤城傲影 2021-01-01 15:30

When defining a generic type parameter\'s constraints, we have to put class() at the front and new() at the end, for example.

Why is this,

2条回答
  •  [愿得一人]
    2021-01-01 16:34

    Like most syntax related questions, the basic answer is because the spec says so. We get the following grammar for generic type constraints from the C# 5.0 spec (Section 10.1.5)

    type-parameter-constraints:

    primary-constraint 
    secondary-constraints
    constructor-constraint 
    primary-constraint   ,   secondary-constraints
    primary-constraint   ,   constructor-constraint 
    secondary-constraints ,   constructor-constraint 
    primary-constraint   ,  secondary-constraints   ,   constructor-constraint 
    

    primary-constraint:

    class-type 
    class 
    struct 
    

    secondary-constraints:

    interface-type
    type-parameter 
    secondary-constraints   ,   interface-type
    secondary-constraints   ,   type-parameter
    

    constructor-constraint:

    new (   )
    

    Eric Lippert has done an excellent job of explaining why it was designed this way, so I won't expound on that.

提交回复
热议问题