静态
类不需要实例即可访问其成员。静态
类不能有实例成员(例如,public int MyNumber;
不允许在静态类上使用,因为只允许在静态类上使用静态成员)。但在非静态类中,实例和静态成员都是允许的。具有protected
构造函数的类只能由它自己或从它继承的类创建一个实例。
public class Program
{
protected Program()
{
// Do something.
}
public static Program Create()
{
// 100% Allowed.
return new Program();
}
public void DoSomething()
{
}
}
public static class AnotherClass
{
public static Program CreateProgram()
{
// Not allowed since Program's constructor is protected.
return new Program();
}
}
public class SubProgram : Program
{
protected SubProgram()
{
// Calls Program() then SubProgram().
}
public new static Program Create()
{
// return new Program(); // We would need to move the SubProgram class INSIDE the Program class in order for this line to work.
return new SubProgram();
}
}
Program.Create(); // Can be called since Create is public and static function.
Program.DoSomething() // Can't be called because an instance has not been instantiated.
var test = Program.Create();
test.DoSomething(); // Can be called since there is now an instance of Program (i.e. 'test').
AnotherClass.CreateProgram(); // Can't be called since Program's constructor is protected.
SubProgram.Create(); // Can be called since SubProgram inherits from Program.
就性能而言,这个区别与性能没有太大关系。
public static class Program {
//...static members
}
或者放置一个受保护/私有的构造函数
public class Program {
protected Program { //OR private
}
//...static members
}
为了防止该类的实例被初始化,可以使用静态类。
静态类与非静态类基本相同,但有一个区别:静态类不能被实例化。
受保护的构造函数意味着只有派生类才能调用构造函数
而私有构造函数将不允许任何其他类使用私有构造函数初始化该类
public class MyClass
{
static readonly long _someStaticMember;
private bool _param;
static MyClass()
{
//Do Some Logic
_someStaticMember = SomeValueCalculated;
}
protected MyClass(bool param)
{
_param = param;
}
}
public class ChildClass: MyClass
{
public ChildClass(bool param) : base(param);
}
public class NotChildClass
{
public MyClass someObject = new MyClass(true); //Will Fail
}
static constr
最多执行一次。触发static constr
的执行是由以下事件中的第一个事件触发的:1.创建类的实例。2.引用类的任何静态成员。 - L. Guthardtstatic constr
最多在给定的应用程序域中执行一次。触发 static constr
的执行是由以下事件中最先发生的事件之一引起的:1. 创建该类的实例。2. 引用该类的任何静态成员。 - L. Guthardt