我试图创建一个打开和保存文件的方法,因为它们的代码非常相似。想要让它更清洁,但不能让它工作。我现在在这里。
我猜FileDialog没问题,但我不知道如何处理SaveFile和LoadFile。
以下是代码:
// Open files
private void atvērtFailuToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenSave(openFileDialog1, LoadFile);
}
// Save files
private void saglabātFailuToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenSave(saveFileDialog1, SaveFile)
}
// Method for both opening and saving files.
private void OpenSave(FileDialog dialog, RichTextBoxStreamType OpenLoad)
{
dialog.Filter = "RTF Files (*.rtf)|*.rtf";
dialog.AddExtension = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
rtf_NotePad.OpenLoad(dialog.FileName, RichTextBoxStreamType.RichText);
}
}
更新 - 它是否正确离开?
private void atvērtFailuToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "RTF Files (*.rtf)|*.rtf";
openFileDialog1.AddExtension = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
rtf_NotePad.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.RichText);
}
}
private void saglabātFailuToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "RTF Files (*.rtf)|*.rtf";
saveFileDialog1.AddExtension = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
rtf_NotePad.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.RichText);
}
}
答案 0 :(得分:1)
Open
和Save
是两个完全不同的操作,虽然从技术上讲,您可以使用bool / enum值在单个方法中混合它们,但它会使您的代码更难以阅读和维护。
如果你想办法让你的手写代码更少:
OpenFileDialog
和SaveFileDialog
SaveFile(path)
,LoadFile(path)
重载。打开:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
rtf_NotePad.LoadFile(openFileDialog1.FileName)
保存:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
rtf_NotePad.SaveFile(saveFileDialog1.FileName)