作者adrianc (123)
看板C_Sharp
标题Re: [问题] 变数宣告在if结构里
时间Mon May 19 12:09:11 2014
看完後整整十分钟心神不宁无法继续工作,决定趁吃饭前回一下。
由原PO回文中已知两个类别是继承关系。
依照原文推文中的Abb大建议,实作程式码。
// 以下程式码依原程式内容
// 预期档案第一行可能读到 "father" or "son" 之外的内容,且不须处理
// 变数命名使用原程式命名方式
private void button1_Click(object sender, EventArgs e)
{
System.IO.StreamReader file = new System.IO.StreamReader("file.txt");
string str = file.ReadLine();
ClassFather xxx = null;
if (str == "father)
{
xxx = new ClassFather();
}
else if (str == "son")
{
xxx = new ClassSon();
}
if (xxx != null)
{
xxx.strA = file.ReadLine();
xxx.strB = file.ReadLine();
}
}
---------------------------------------------------------------
ClassFather xxx = null;
.
.
.
xxx = new ClassSon();
}
这段视你的需求可以考虑用
ClassFather xxx = FatherSonClassFactory.Create(str);
来替换掉
然後 C# (物件导向) 的 method 主要功能应该不是用来排版..
※ 引述《LetsGoToEat (一起去吃东西吧)》之铭言:
: ※ 引述《GoalBased (Artificail Intelligence)》之铭言:
: : 大概是长这样,细节有错的话自己改,
: : 是说..现在的新手会开档读档,会用类别,不会用function是怎麽回事= =
: 感谢帮忙,我试着改成这样
: private void button1_Click(object sender, EventArgs e)
: {
: System.IO.StreamReader file = new System.IO.StreamReader("file.txt");
: string str = file.ReadLine();
: if (str == "father")
: {
: ClassFather xxx = new ClassFather();
: IamFunction(file, xxx);
: }
: else if (str == "son")
: {
: ClassSon xxx = new ClassSon();
: IamFunction(file, xxx);
: }
: }
: private void IamFunction(System.IO.StreamReader file, ClassFather xxx)
: {
: xxx.strA = file.ReadLine();
: xxx.strB = file.ReadLine();
: }
: 似乎是可以了@@
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 220.134.109.209
※ 文章网址: http://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1400472554.A.5E1.html