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

作者: GoalBased (Artificail Intelligence)   2014-05-18 12:28:23
※ 引述《LetsGoToEat (一起去吃東西吧)》之銘言:
: 請教一下,原本寫讀取紀錄變數的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程式碼都長一樣,
: 有沒有只要寫一次的方法呢,新手不知道該搜尋什麼關鍵字,
: 還請多見諒
if (str == "Father")
{
ClassFather xxx = new ClassFather();
IamFunction();
}
else if (str == "Son")
{
ClassSon xxx = new ClassSon();
IamFunction();
}
protected void IamFunction()
{
str = file.ReadLine();
xxx.strA = str;
str = file.ReadLine();
xxx.strB = str;
}
大概是長這樣,細節有錯的話自己改,
是說..現在的新手會開檔讀檔,會用類別,不會用function是怎麼回事= =
作者: LetsGoToEat (一起去吃東西吧)   2014-05-18 13:21:00
我讀檔是寫在button的click方法裡 不知變數在哪宣告

Links booklink

Contact Us: admin [ a t ] ucptt.com