What's the difference between an abstract class and a static one?

后端 未结 9 1909
臣服心动
臣服心动 2020-12-02 18:55

Neither is instantiable. What are the differences, and in what situations might you use one or the other?

9条回答
  •  独厮守ぢ
    2020-12-02 19:03

    The CLR has no notion of static classes, it is specific to C#. The compiler implements it by slick use of CLR attributes for a class: it declares it abstract and sealed. That prevents any language from instantiating such a class. This is what it looks like when you run Ildasm:

    .class public abstract auto ansi sealed beforefieldinit ConsoleApplication1.Test
           extends [mscorlib]System.Object
    {
    }
    

    Making it sealed is very much the point of a static class, it is used as a container for static methods and fields. Which makes them act like global variables and functions like you have in languages like C or Pascal.

    An abstract class is very much the opposite, it is designed to be derived from. A abstract class that has all of its member abstract acts like an interface. C# has a keyword for that, making static class and interface the exact opposites.

提交回复
热议问题