Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

c# - Why is some ordering enforced in generic parameter constraints?

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, why can't I put my constraints in any order?

Are there any other restrictions on ordering besides class/struct first, new() at the end?


Example:

protected T Clone<T>() where T : class, ICopyable<T>, new()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's no particular reason why that order was chosen. The chosen order goes from more general to more specific, which I suppose is a reasonably nice property.

As for the question "why require an order at all?", it's simply easier on the implementation and testing teams to have a clear, unambiguous order imposed by the language. We could allow the constraints to come in any order, but what does that buy us?

The longer I work on languages the more I'm of the opinion that every time you give the user a choice, you give them an opportunity to make a bad choice. A basic design principle of C# is that we tell you when things look wrong and force you to make them right -- which is not a basic design principle of, say, JavaScript. Its basic design principle is "muddle on through and try to do what the user meant". By placing more restrictions on what is correct syntax in C# we can better ensure that the intended semantics are expressed well in the program.

For example, if I were designing a C#-like language today there is no way that I would have ambiguous syntaxes like:

class C : X , Y

or

... where T : X, Y

Y is clearly intended to be an interface. Is X? We can't tell syntactically whether X was intended to be an interface or a class. Suffice to say this ambiguity greatly complicates things like detecting cycles in base types vs interfaces and so on. It'd be much easier on all concerned if it were more verbose, as it is in VB.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...