Why must the base class be specified before interfaces when declaring a derived class?
public interface ITest
{
int开发者_StackOverflow中文版 ChildCount { get; set; }
}
public class Test
{
}
public class OrderPool : ITest, Test
{
public int ChildCount
{
get;
set;
}
}
The error says Base class 'Test' must come before any interfaces. Why is it necessary to extend the class first and then implement the inteface?
Because the specification says so in section §17.1.2.
C# supports only single inheritance, but allows classes to implement multiple interfaces. That being the case, it's much clearer to always have the base class specified in the same place by convention, rather than mixed in with a bunch of interfaces.
Regardless of convention, the specification mandates that this is the case anyway, which is why you're seeing that error.
Remember, there's nothing in the specification that says all of your interfaces have to be named with a capital "I". - that's just convention. So if your class implemented interfaces that didn't follow that convention, and if the specification allowed you to specify the base class and interfaces in any order, you wouldn't be able to easily tell which identifier was the base class and which were interfaces. Example:
class MyDerivedClass : A, B, C, D, E // which is the base class?
{
...
}
it's called syntax
There are conventions that you must follow in order for the compiler to compile the code.
They could have chosen to allow both forms, or just the other way around, but they didn't. The reason is probably clarity : you can define a lot of interfaces and only inherit from one class.
Technically it would have been possible to allow them all in random order, but that would make the code less readable.
Simply because the language is designed like that. The reason is probably that a class can have only one base class, but implement any number of interfaces.
Because you can extend just one class and implements more than one interface, having the class first make easier to read. And probably the grammar itself is easyer to write that way, just a pseudo grammar could be:
class CLASSNAME:baseclass? interface*
meaning optional baseclass followed by many interface, writing one grammar that allow just one class messed somewhere would be difficult without any reason.
You can only inherit from one base class but many interfaces. So if there is more than one type listed you know that the first one is a class, the others interfaces. This works regardless of class/interface naming conventions
The order makes clear sense, the base class can implement members of the interface for the derived class, therefore the compiler must know of them beforehand
精彩评论