你這樣寫會讓其他人亂用繼承關係。
原PO的解答的確是要用多型,Abb大寫的沒錯。
但是「如何寫」是一回事,
你有用到DesignPattern的概念,寫出來的東西卻打了自己一巴掌。
====文字檔====
文字檔Father.txt
Father
My name is Darth Vader.
I am your Father!
文字檔Son.txt
Son
My name is Luke Skywalker.
No~~~~~~~~~!
====程式碼====
程式碼Family.cs
abstract public class Family
{
public string StrA { get; set; }
public string StrB { get; set; }
public Family(StreamReader reader)
{
this.StrA = reader.ReadLine();
this.StrB = reader.ReadLine();
}
public abstract void ShowStrA();
public abstract void ShowStrB();
}
程式碼Father.cs
public class Father : Family
{
public Father(StreamReader reader)
: base(reader)
{
}
public override void ShowStrA()
{
Console.WriteLine(this.StrA);
}
public override void ShowStrB()
{
Console.WriteLine(this.StrB);
}
}
程式碼Son.cs
public class Son : Family
{
public Son(StreamReader reader)
: base(reader)
{
}
public override void ShowStrA()
{
Console.WriteLine(this.StrA);
}
public override void ShowStrB()
{
Console.WriteLine(this.StrB);
}
}
程式碼FamilyFactory.cs
public class FamilyFactory
{
public static Family CreateFamily(string familyMember, StreamReader
reader)
{
if (familyMember == "Father")
{
return new Father(reader);
}
else if (familyMember == "Son")
{
return new Son(reader);
}
else
{
return null;
}
}
}
客戶端調用
StreamReader reader1 = new StreamReader("Father.txt");
StreamReader reader2 = new StreamReader("Son.txt");
string familyMember1 = reader1.ReadLine();
string familyMember2 = reader2.ReadLine();
Family family1 = FamilyFactory.CreateFamily(familyMember1, reader1);
Family family2 = FamilyFactory.CreateFamily(familyMember2, reader2);
family1.ShowStrA();
family2.ShowStrA();
family1.ShowStrB();
family2.ShowStrB();
結果
My name is Darth Vader.
My name is Luke Skywalker.
I am your Father!
No~~~~~~~~~!
Father類別或Son類別是不同的,
只有新手或不熟悉物件導向的人才會直接用Son來繼承Faher,
這兩個類別都應該抽像於Family類別,
這樣子寫才比較好維護也有彈性。
Abb大說的多型是這樣,
只不過我偷懶把strA跟strB的readline寫在建構式。
※ 引述《adrianc (123)》之銘言:
: 看完後整整十分鐘心神不寧無法繼續工作,決定趁吃飯前回一下。
: 由原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();
: }
: }
: