今天是第三版,和前幾天一樣今天還是要對代碼進行優化,三層架構是一種思想,具體能不能使得整個系統安全和高性能,還是要看代碼編寫的是否合理,邏輯性是否嚴謹。
昨天偶然間看到別人寫的三層架構中,竟然沒有在方法中傳遞單個參數,而是直接聲明了一個對象整體的當傳參。最后上網查,發現原來是在系統里多加了一層,叫做模型層,就是用來在系統的各層之間傳遞數據的,這樣就避免了為一個方法傳遞多個參數現象。
具體深入的模型層使用還在學習當中,今天就用學到的一點簡單的模型層知識,對代碼進行再一次優化。
首相先建立一個模型層(Model)在里面創建一個實體類(person):
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Model 8 { 9 public class person10 {11 //員工編號12 public string id;13 14 public string Id15 {16 get { return id; }17 set { id = value; }18 }19 20 //員工姓名21 public string name;22 23 public string Name24 {25 get { return name; }26 set { name = value; }27 }28 29 //員工性別30 public string sex;31 32 public string Sex33 {34 get { return sex; }35 set { sex = value; }36 }37 38 //員工工資39 public string salary;40 41 public string Salary42 {43 get { return salary; }44 set { salary = value; }45 }46 47 //構造函數,無參48 public person()49 {50 51 }52 53 //構造函數,傳入一個參數 id54 public person(string id)55 {56 this.id = id;57 }58 59 //構造函數,傳入三個參數 name, sex, salary60 public person(string name, string sex, string salary)61 {62 this.name = name;63 64 this.sex = sex;65 66 this.salary = salary;67 }68 69 //構造函數,傳入四個參數 id, name, sex, salary70 public person(string id, string name, string sex, string salary)71 {72 this.id = id;73 74 this.name = name;75 76 this.sex = sex;77 78 this.salary = salary;79 }80 }81 }
然后對之前的代碼進行簡單的修改,在這里就不發出全部方法的更改了,其它方法類似:
先引入模型層(Model):
using Model;
default.aspx.cs代碼:
1 //更改員工信息 2 PRotected void update_Click(object sender, EventArgs e) 3 { 4 string id = this.update_id.Text.Trim(); 5 6 string name = this.update_name.Text.Trim(); 7 8 string sex = this.update_sex.Text.Trim(); 9 10 string salary = this.update_salary.Text.Trim();11 12 person p = new person(id, name, sex, salary);13 14 if (pd.update(p))15 {16 this.lbl_3.Text = " * 更改成功!";17 }18 }
personDAO類:
1 public bool update(person p) 2 { 3 bool flag = false; 4 5 SqlParameter[] paras = new SqlParameter[]//創建參數數組 6 { 7 new SqlParameter("@id", p.id), 8 new SqlParameter("@name", p.name), 9 new SqlParameter("@sex", p.sex),10 new SqlParameter("@salary", p.salary)11 };12 13 //使用參數數組里的值14 string sql = "update person set [name] = @id, sex = @name, salary = @sex where id = salary";15 16 if (sq.ExecuteNonQuery(sql, paras) > 0)17 {18 flag = true;19 }20 21 return flag;22 }
SQLHelper類(不改變):
1 /// <summary> 2 /// 執行帶參數的增刪改SQL語句 3 /// </summary> 4 /// <param name="sql">要執行的SQL語句</param> 5 /// <param name="paras">傳入的參數</param> 6 /// <returns>返回受影響的行數</returns> 7 public int ExecuteNonQuery(string sql, SqlParameter[] paras) 8 { 9 int res;10 11 cmd = new SqlCommand(sql, getcon());12 13 cmd.Parameters.AddRange(paras);16 17 res = cmd.ExecuteNonQuery();18 19 return res;20 }
*實體類的使用,在小項目里效果不明顯,因此有很多人說,實體類可有可無,但是真正到了大型項目里面,實體類的使用使得整個系統變得更加流暢,緊密,邏輯性也更好。
新聞熱點
疑難解答