在我的Wpf应用程序中,我使用的是Person类(即基类),它包含一个虚方法SaveData(),以及其他继承自Person的类Client.如何覆盖方法SaveData()并保持数据从基数?
班级人员
public virtual void SaveData()
{
string arqName = string.Format("Person{0}" + ".txt", Id);
StreamWriter file = new StreamWriter(arqNome);
file.WriteLine("ID: " + Id);
file.WriteLine("DOB: " + dOB);
file.WriteLine("Name: " + name);
file.WriteLine("Age: " + age);
file.Flush();
file.Close();
}
类客户
public override void SaveData()
{
base.SaveData();
string arqName = string.Format("Person{0}" + ".txt", Id);
StreamWriter file = new StreamWriter(arqNome);
file.WriteLine("Cod: " + cod);
file.WriteLine("Credits: " + credits);
file.Flush();
file.Close();
}
客户端中的覆盖方法确实覆盖了其他数据,如Name,Age,DOB ……我需要在同一个文件中保留两者.
解决方法:
StreamWriter是流装饰器,因此您可以更好地实例化FileStream并将其传递给StreamWriter构造函数.因此,您可以自定义它.追加模式打开文件并将指针移动到文件末尾,因此您要编写的下一个内容将被追加.并使用using指令显式调用Close():
Person类SaveData():
using (var fileStream = new FileStream(String.Format("Person{0}.txt", Id), FileMode.OpenOrCreate))
using (var streamWriter = new StreamWriter(fileStream))
{
streamWriter.WriteLine("ID: " + Id);
streamWriter.WriteLine("DOB: " + dOB);
streamWriter.WriteLine("Name: " + name);
streamWriter.WriteLine("Age: " + age);
}
客户端类SaveData():
base.SaveData();
using (var fileStream = new FileStream(String.Format("Person{0}.txt", Id), FileMode.Append))
using (var streamWriter = new StreamWriter(fileStream))
{
streamWriter.WriteLine("Cod: " + cod);
streamWriter.WriteLine("Credits: " + credits);
}