What is a “static” class?

后端 未结 10 1363
面向向阳花
面向向阳花 2020-12-04 16:35

In C# what is the difference between:

public static class ClassName {}

And:

public class ClassName {}
相关标签:
10条回答
  • 2020-12-04 17:06

    Static class can contain static members only.

    Static member can be used without instantiating a class first.

    0 讨论(0)
  • 2020-12-04 17:10

    All methods/properties in a static class must be static, whereas a 'normal' class can contain a mix of instance and static methods.

    0 讨论(0)
  • 2020-12-04 17:12

    You can't instantiate (create objects of) a static class. And it can only contain static members.

    Example: System.Math

    0 讨论(0)
  • 2020-12-04 17:15

    A static class cannot be instantiated, and can contain only static members. Hence, the calls for a static class are as: MyStaticClass.MyMethod(...) or MyStaticClass.MyConstant.

    A non static class can be instantiated and may contain non-static members (instance constructors, destructor, indexers). A non-static member of a non-static class is callable only through an object:

    MyNonStaticClass x = new MyNonStaticClass(...);
    x.MyNonStaticMethod(...);
    
    0 讨论(0)
  • 2020-12-04 17:15

    A static class also can not be inherited from, whereas a non-static class with static members can be inherited from.

    0 讨论(0)
  • 2020-12-04 17:16
    public static class ClassName {}
    

    A static class is just like a global variable: you can use it anywhere in your code without instantiating them. For example: ClassName. After the dot operator, you can use any property or function of it.

     public class ClassName {}
    

    But if you have non-static class then you need to create an instance of this class. For example:

     ClassName classNameObject = new ClassName(); 
    
    0 讨论(0)
提交回复
热议问题