What is a “static” class?

2019-01-21 08:51发布

In C# what is the difference between:

public static class ClassName {}

And:

public class ClassName {}

10条回答
看我几分像从前
2楼-- · 2019-01-21 09:33

http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html - very good article on this. This is for Java. But i think concept should should same in C# too.

查看更多
走好不送
3楼-- · 2019-01-21 09:33

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(...);
查看更多
Melony?
4楼-- · 2019-01-21 09:37

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

Example: System.Math

查看更多
小情绪 Triste *
5楼-- · 2019-01-21 09:38

Static classes and members are used to create data and methods that can be accessed without creating an instance (using the new keyword, they cannot have a constructor) of the class.

Static classes can be declared when there is no dependence on the its own object identity, so a static class must contain only static members.

This classes are loaded by the CLR when the program or namespace containing the class is loaded.

They are also sealed, cannot be inherited from.

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-21 09:44
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(); 
查看更多
够拽才男人
7楼-- · 2019-01-21 09:45

Static class can contain static members only.

Static member can be used without instantiating a class first.

查看更多
登录 后发表回答