静态类和非静态类的区别
class ExampleTest
{
static ExampleTest()
{
Console.WriteLine("test static default constructor in unstatic class");
}
public ExampleTest()
{
Console.WriteLine("test default constructor in unstaic class");
}
}
static class ExampleTest2
{
static ExampleTest2()
{
Console.WriteLine("test static Method in static class");
}
#region 静态类不能调用实例构造函数
//public ExampleTest2()
//{
// Console.WriteLine("test unstatic method in static class");
//}
#endregion
#region 静态类中不能调用实例方法
//public void getAlert()
//{
// Console.WriteLine("Alert,alert");
//}
#endregion
public static void getAlert()
{
Console.WriteLine("Alert,alert");
}
}
{
static ExampleTest()
{
Console.WriteLine("test static default constructor in unstatic class");
}
public ExampleTest()
{
Console.WriteLine("test default constructor in unstaic class");
}
}
static class ExampleTest2
{
static ExampleTest2()
{
Console.WriteLine("test static Method in static class");
}
#region 静态类不能调用实例构造函数
//public ExampleTest2()
//{
// Console.WriteLine("test unstatic method in static class");
//}
#endregion
#region 静态类中不能调用实例方法
//public void getAlert()
//{
// Console.WriteLine("Alert,alert");
//}
#endregion
public static void getAlert()
{
Console.WriteLine("Alert,alert");
}
}
从上面两个类中,我们得到结论:
1、构造函数,无论在静态类或非静态类中,如果我们定义了一个static的构造函数,那么只要创建这个类的实例或调用这个类的方法,都将自动调用这个Static的构造函数,并且Static的构造函数是不能有访问权限的。static的构造函数是不能有参数的。
2、静态类中不能调用实例构造函数
2、静态类中不能创建非静态的方法。即静态方法中只能创建静态方法,但在非静态类中可以调用静态方法(这个情况我们经常使用的)

浙公网安备 33010602011771号