-------------------------------------2345王牌技术员联盟、2345王牌技术员联盟、期待与您交流!-----------------------------------------
1.静态构造函数
C#中可以给类编写无参的静态构造函数。无参静态函数只执行一次,但是非静态构造函数是实例构造函数,只要创建对象就会调用。
class Program
{
static Program()
{
//do something
}
}
一般静态构造函数主要作用是,类有些静态字段或属性需要在第一次使用类之前,从外部源中初始化这些静态字段和属性。
需要注意的是:
1.静态构造函数在什么时候执行并不能确定,不同类的静态构造函数执行顺序也无法确定。但静态构造函数至多只能执行一次,通常是在第一次调用类的任何成员之前执行静态构造函数。
2.静态构造函数没有访问修饰符。因为其他的代码从来不调用它,只是在加载类时由.NET运行库调用它,所以访问修饰符对其没有任何意义。也正是同样原因,静态构造函数不能带参数,一个类只能有一个静态构造函数。
3.静态构造函数只能访问类的静态成员。
4.无参数的实力构造函数与静态构造函数可以在同一个类中同时定义。
例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace PreprocessorDirectivePractice
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("today's backcolor is :" + Test.BackColor);
Console.ReadKey();
}
}
public class Test
{
public static readonly Color BackColor;
static Test()
{
DateTime now = DateTime.Now;
if (now.DayOfWeek == DayOfWeek.Saturday || now.DayOfWeek == DayOfWeek.Sunday)
{
BackColor = Color.Red;
}
else
{
BackColor = Color.Green;
}
}
private Test()
{ }
}
}
2.从构造函数中调用其他构造函数
有时在一个类中有几个构造函数,以容纳某些可选参数,这些构造函数包含一些共同的代码:
class Car
{
private string description;
private int wheels;
public Car(string description,int wheels)
{
this.description = description;
this.wheels=wheels;
}
public Car(string description)
{
this.description=description;
this.wheels=4;
}
}
因为两个构造函数初始化了相同的字段,所以为了简便可以使用构造函数初始化器来使一个构造函数调用另一个:
class Car
{
private string description;
private int wheels;
public Car(string description,int wheels)
{
this.description = description;
this.wheels=wheels;
}
public Car(string description):this(description,4)
{
}
}
这里,this关键字仅调用参数最匹配的那个构造函数。注:构造函数初始化器在构造函数的函数体之前执行。
下面是运行代码:
Car myCar = new Car("benz")
这段代码中一个参数的构造函数是在两个函数的构造函数之后执行的。
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace PreprocessorDirectivePractice
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("today's backcolor is :" + Test.BackColor);
Console.ReadKey();
}
}
public class Test
{
public static readonly Color BackColor;
static Test()
{
DateTime now = DateTime.Now;
if (now.DayOfWeek == DayOfWeek.Saturday || now.DayOfWeek == DayOfWeek.Sunday)
{
BackColor = Color.Red;
}
else
{
BackColor = Color.Green;
}
}
private Test()
{ }
}
}
构造函数初始化器也可以包含对直接父类的构造函数的调用(用base关键字代替this)。初始化器中不能有多个调用。
---------------------------------------2345王牌技术员联盟、2345王牌技术员联盟、期待与您交流!----------------------------------------