不忘本~静态构造函数
静态构造函数用于初始化任何静态数据,或用于执行仅需执行一次的特定操作。
在创建第一个实例或引用任何静态成员之前,将自动调用静态构造函数.(注意,当你在本地调试一个网站项目中设置静态构造函数的话,它在IE没有被关闭之前,静态构架方法为静态字段赋值是不变的,它只有再你下次运行网站时,它才会发生变化)
1 class Program 2 3 { 4 5 static void Main(string[] args) 6 7 { 8 9 static_construct sc = new static_construct(); //这里它执行了普通构造方法和静态构造方法 10 11 static_construct sc2 = new static_construct(); //这里静态构造方法就不会被执行了,它只在第一个类实例时被执行 12 13 Console.WriteLine(static_construct.A); 14 15 Console.ReadKey(); 16 17 } 18 19 } 20 21 22 23 class static_construct 24 25 { 26 27 static int a = 0; 28 29 public static_construct() 30 31 { 32 33 a += 1; 34 35 } 36 37 38 39 static static_construct() 40 41 { 42 43 a += 3; 44 45 } 46 47 public static int A { get { return a; } } 48 49 public static string Info { get; set; } 50 51 }
1 public class DepartmentsService : IDepartmentsService 2 { 3 static Data.OA.IDepentmentsRepository iDepentmentsRepository = new Data.OA.DepentmentsRepository(); 4 5 static List<Entity.OA.Department> entitiesList = null; 6 7 /// <summary> 8 /// 静态构造方法,在使用任何静态成员之前会被提前执行 9 /// </summary> 10 static DepartmentsService() 11 12 { 13 14 Reload(); 15 16 } 17 18 19 internal static void Reload() 20 21 { 22 23 entitiesList = (from pc in iDepentmentsRepository.GetDepentments() 24 25 orderby pc.DeptName ascending 26 27 select pc).ToList(); 28 29 } 30 31 #region 树型部门列表 32 33 /// <summary> 34 35 /// 虚拟产品类别 36 37 /// </summary> 38 39 /// <returns>虚拟产品类别列表</returns> 40 41 public static Entity.OA.Department GetTree() 42 43 { 44 45 Entity.OA.Department root = new Entity.OA.Department(); 46 47 try 48 49 { 50 51 root = entitiesList.Single( 52 53 item => item.DeptID.Equals(Entity.OA.Department.ROOTID));//获取跟节点 54 55 GetSubs(root); 56 57 } 58 59 catch (InvalidOperationException ex) 60 61 { 62 63 ex.ToString(); 64 65 } 66 67 return root; 68 69 } 70 71 /// <summary> 72 73 /// 根据父对象,找到子孙树 74 75 /// </summary> 76 77 /// <param name="father">父对象</param> 78 79 static public void GetSubs(Entity.OA.Department father) 80 81 { 82 83 father.SubList = entitiesList.Where(item => 84 85 item.ParentID.Equals(father.DeptID)).ToList(); 86 87 father.SubList.ForEach(item => 88 89 { 90 91 item.Father = father; 92 93 GetSubs(item); 94 95 }); 96 97 } 98 99 #endregion 100 }