“Cannot create an instance of the abstract class or interface” C# error message

前端 未结 3 990
傲寒
傲寒 2020-12-19 06:09

I changed my base class to abstract for a project and now I\'m receiving the following error:

Cannot create an instance of the abstract c

3条回答
  •  半阙折子戏
    2020-12-19 06:57

    I saw your earlier question, in which you asked about the meaning of "pure virtual" (abstract in C#).

    The reason you cannot instantiate an abstract class is that it presumably has abstract members, with no implementation. So say your class looks like this:

    abstract class Airplane_Abstract
    {
        public abstract int GetSomeInteger();
    }
    

    Then assuming you could instantiate one of these, you could write code like this:

    var airplane = new Airplane_Abstract();
    
    // What would this be?
    int integer = airplane.GetSomeInteger();
    

    Granted, I don't believe you actually have to have abstract members in an abstract class. But the general idea of an abstract class is that it's one that cannot exist on its own; it must be further defined in a class which inherits from it. Abstract members are the most obvious illustration of why this would be; there could be other reasons.

    Think of Shape, for example. This is a pretty common example of something that would make sense as an abstract class. You can't really instantiate just a Shape, can you? ("Create a shape." "What kind of shape?" "No kind. Just an abstract shape." Doesn't really work, does it?)

提交回复
热议问题