Why must the base class be specified before interfaces when declaring a derived class?

后端 未结 7 1714
伪装坚强ぢ
伪装坚强ぢ 2020-12-19 06:54
public interface ITest
{
    int ChildCount { get; set; }
}

public class Test
{
}

public class OrderPool : ITest, Test
{
    public int ChildCount
    {
        ge         


        
相关标签:
7条回答
  • 2020-12-19 07:09

    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?  
    {
    ...
    }
    
    0 讨论(0)
  • 2020-12-19 07:18

    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.

    0 讨论(0)
  • 2020-12-19 07:20

    Because the specification says so in section §17.1.2.

    0 讨论(0)
  • 2020-12-19 07:21

    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

    0 讨论(0)
  • 2020-12-19 07:25

    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.

    0 讨论(0)
  • 2020-12-19 07:35

    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.

    0 讨论(0)
提交回复
热议问题