Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

c# - What is a "static" class?

In C# what is the difference between:

public static class ClassName {}

And:

public class ClassName {}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Firstly, a comment on an answer asked about what "static" means. In C# terms, "static" means "relating to the type itself, rather than an instance of the type." You access a static member (from another type) using the type name instead of a reference or a value. For example:

// Static method, so called using type name
Guid someGuid = Guid.NewGuid();
// Instance method, called on a value
string asString = someGuid.ToString();

Now, static classes...

Static classes are usually used as "utility" classes. The canonical example is probably System.Math. It doesn't make sense to create an instance of math - it just "is". A few rules (both "can" and "can't"):

  • Static classes always derive from object. You can't specify a different base type, or make the static class implement an interface.
  • Static classes can't have any instance members - all variables, methods etc must be static.
  • Static classes can't declare any instance constructors and the compiler doesn't create a parameterless constructor by default. (Before static classes came in C# 2.0, people would often create an abstract class with a private constructor, which prevented instantiation. No need here.)
  • Static classes are implicitly abstract (i.e. they're compiled to IL which describes an abstract class) but you can't add the abstract modifier yourself.
  • Static classes are implicitly sealed (i.e. they're compiled to IL which describes an sealed class) but you can't add the sealed modifier yourself.
  • Static classes may be generic.
  • Static classes may be nested, in either non-static or static classes.
  • Static classes may have nested types, either non-static or static.
  • Only static, top-level non-generic classes can contain extension methods (C# 3.0).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...