静态构造函数用于初始化任何静态数据,或用于执行仅需执行一次的特定操作。
在创建第一个实例或引用任何静态成员之前,将自动调用静态构造函数
class Program
{
static void Main(string[] args)
{
static_construct sc = new static_construct(); //这里它执行了普通构造方法和静态构造方法
static_construct sc2 = new static_construct(); //这里静态构造方法就不会被执行了,它只在第一个类实例时被执行
Console.WriteLine(static_construct.A);
Console.ReadKey();
}
}
class static_construct
{
static int a = 0;
public static_construct()
{
a += 1;
}
static static_construct()
{
a += 3;
}
public static int A { get { return a; } }
public static string Info { get; set; }
}
以下是一个树型部门的例子:
public class DepartmentsService : IDepartmentsService
{
static Data.OA.IDepentmentsRepository iDepentmentsRepository = new Data.OA.DepentmentsRepository();
static List<Entity.OA.Department> entitiesList = null;
/// <summary>
/// 静态构造方法,在使用任何静态成员之前会被提前执行
/// </summary>
static DepartmentsService()
{
Reload();
}
internal static void Reload()
{
entitiesList = (from pc in iDepentmentsRepository.GetDepentments()
orderby pc.DeptName ascending
select pc).ToList();
}
#region 树型部门列表
/// <summary>
/// 虚拟产品类别
/// </summary>
/// <returns>虚拟产品类别列表</returns>
public static Entity.OA.Department GetTree()
{
Entity.OA.Department root = new Entity.OA.Department();
try
{
root = entitiesList.Single(
item => item.DeptID.Equals(Entity.OA.Department.ROOTID));//获取跟节点
GetSubs(root);
}
catch (InvalidOperationException ex)
{
ex.ToString();
}
return root;
}
/// <summary>
/// 根据父对象,找到子孙树
/// </summary>
/// <param name="father">父对象</param>
static public void GetSubs(Entity.OA.Department father)
{
father.SubList = entitiesList.Where(item =>
item.ParentID.Equals(father.DeptID)).ToList();
father.SubList.ForEach(item =>
{
item.Father = father;
GetSubs(item);
});
}
#endregion
}