[問題] 變數宣告在if結構裡

看板C_Sharp作者 (一起去吃東西吧)時間10年前 (2014/05/18 11:49), 編輯推噓1(102)
留言3則, 3人參與, 最新討論串1/5 (看更多)
請教一下,原本寫讀取紀錄變數的txt檔,類似這樣 System.IO.StreamReader file = new System.IO.StreamReader("file.txt"); ClassFather xxx = new ClassFather(); string str = file.ReadLine(); xxx.strA = str; str = file.ReadLine(); xxx.strB = str; 後來改寫,想由文字檔的第一行判斷要用父或子類別,之後的處理都一樣的 System.IO.StreamReader file = new System.IO.StreamReader("file.txt"); string str = file.ReadLine(); if (str == "Father") { ClassFather xxx = new ClassFather(); str = file.ReadLine(); xxx.strA = str; str = file.ReadLine(); xxx.strB = str; } else if (str == "Son") { ClassSon xxx = new ClassSon(); str = file.ReadLine(); xxx.strA = str; str = file.ReadLine(); xxx.strB = str; } 因為後面的xxx.strA和xxx.strB程式碼都長一樣, 有沒有只要寫一次的方法呢,新手不知道該搜尋什麼關鍵字, 還請多見諒 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 42.69.93.23 ※ 文章網址: http://www.ptt.cc/bbs/C_Sharp/M.1400384977.A.ABA.html

05/18 12:04, , 1F
拆成function
05/18 12:04, 1F

05/18 12:11, , 2F
嗚還是不會Q_Q
05/18 12:11, 2F

05/18 16:09, , 3F
你的父和子是繼承關係的話用多型
05/18 16:09, 3F
文章代碼(AID): #1JU2tHgw (C_Sharp)
文章代碼(AID): #1JU2tHgw (C_Sharp)