不忘本~靜態構造函數
靜態構造函數用于初始化任何靜態數據,或用于執行僅需執行一次的特定操作。
在創建第一個實例或引用任何靜態成員之前,將自動調用靜態構造函數.(注意,當你在本地調試一個網站項目中設置靜態構造函數的話,它在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 }
浙公網安備 33010602011771號