在 C# 中有什么区别:
public static class ClassName {}
和:
public class ClassName {}
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"):
object
. You can't specify a different base type, or make the static class implement an interface.abstract
modifier yourself.sealed
modifier yourself.静态类不能被实例化,并且只能包含静态成员。因此,对静态类的调用如下:MyStaticClass.MyMethod(...)
或MyStaticClass.MyConstant
。
非静态类可以被实例化并且可以包含非静态成员(实例构造函数、析构函数、索引器)。非静态类的非静态成员只能通过对象调用:
MyNonStaticClass x = new MyNonStaticClass(...);
x.MyNonStaticMethod(...);
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();
静态类也不能被继承,而具有静态成员的非静态类可以被继承。
静态类中的所有方法/属性都必须是静态的,而“普通”类可以包含实例和静态方法的混合。
静态类只能包含静态成员。
可以在不先实例化类的情况下使用静态成员。
您不能实例化(创建对象)静态类。它只能包含静态成员。
示例:System.Math
静态类和成员用于创建无需创建类的实例(使用new
关键字,它们不能有构造函数)即可访问的数据和方法。
静态类可以在不依赖其自身的对象标识时声明,因此静态类必须只包含静态成员。
当加载包含该类的程序或命名空间时,CLR 会加载此类。
它们也是密封的,不能继承。
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.
Static variable in c
a variable local to a class as auto variables but static variable do not disappear as function is no longer active.Their values persist.If control comes back,static variables have same value
static function in c functions that are not visible to functions in other files.
*static data members in cpp * data members can be variables or functions in cpp static applies to both data members the class itself can be static "There is only one copy of static data memberss shared by all objects in that class" static data members can access only static data members
static class this class cannot instantiate objects
Most importantly, "A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides." - From Microsoft