Can you enforce the same constraint on multiple ge

2020-05-08 07:31发布

问题:

I know you can you can do it like this:

void M<T1, T2, T3>() where T1 : S where T2 : S where T3 : S 
{}

I want something like this:

void M<T1, T2, T3>() where T1, T2, T3 : S 
{}

Is there any such shortcut?

回答1:

No, that is not supported. The C# language spec states

Each type-parameter-constraint-clause consists of the token where, followed by the name of a type parameter, followed by a colon and the list of constraints for that type parameter.

The key here is a, indicating that the grammer requires where <TypeParam> : <Constraint1>,<Constraint2>, etc.. .