作者LetsGoToEat (一起去吃东西吧)
看板C_Sharp
标题[问题] 变数宣告在if结构里
时间Sun May 18 11:49:35 2014
请教一下,原本写读取纪录变数的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://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1400384977.A.ABA.html
1F:→ yuhaw0715:拆成function 05/18 12:04
2F:→ LetsGoToEat:呜还是不会Q_Q 05/18 12:11
3F:推 Abbee:你的父和子是继承关系的话用多型 05/18 16:09