【问题标题】:C# StreamWriter in separate classC# StreamWriter 在单独的类中
【发布时间】:2016-02-03 10:39:36
【问题描述】:

我在 form1 中有一个文本框和一个按钮,当我在文本框中写入时,我可以使用我的按钮将其保存到计算机上的文件中。这是放在我的按钮内

    public void button1_Click(object sender, EventArgs e)
    {
        string FileName = "C:\\sample\\sample.txt";
        System.IO.StreamWriter WriteToFile;
        WriteToFile = new System.IO.StreamWriter(FileName);
        WriteToFile.Write(textBox1.Text);
        WriteToFile.Close();
        MessageBox.Show("Succeded, written to file");

但无论如何,我想将与 streamWriter 相关的所有内容移到他们自己的类 (Class1) 中,并从按钮内的主窗体中调用它。 如果我将所有内容移到 Button 中并将其移到方法内的 class1 中,则它声称 Textbox1 不存在,很明显。

对于我应该阅读更多内容,您有任何提示或链接吗?

最好的问候 数据库

【问题讨论】:

  • 传递textBox1.Text作为方法的参数
  • 作为最佳实践,我还建议在 using 语句中打开 StreamWriter,或者让使用它的类实现 IDisposable 接口

标签: c# winforms class methods streamwriter


【解决方案1】:

你可以在课堂上这样做:

public class MyClass {
    public static bool WriteToFile(string text){
        string FileName = "C:\\sample\\sample.txt";
        try {
            using(System.IO.StreamWriter WriteToFile = new System.IO.StreamWriter(FileName)){
                WriteToFile.Write(text);
                WriteToFile.Close();
            }
            return true;
        }
        catch {
            return false;
        }
    }
}

在你的按钮事件中:

public void button1_Click(object sender, EventArgs e){
    if(MyClass.WriteToFile(textBox1.Text))
        MessageBox.Show("Succeded, written to file");
    else
        MessageBox.Show("Failer, nothing written to file");
}

【讨论】:

  • 我会将 MessageBox 调用从类移动到调用该方法的位置。还向 WriteToFile 方法添加一些错误处理,并可选择让它返回一个 bool 表示成功/失败。
  • 对于像这样简单的事情,我会将其设为静态函数/类,因此您只需调用 MyClass.WriteToFile(textBox1.Text); 同样,如前所述,使其返回具有成功状态的布尔值。
  • Racil Hilan,感谢您的解释。我会将您的答案标记为已接受。我的问题是我不知道如何将 textBox1 传递给我的方法。我也忘了添加一个 in 参数。我还会检查您的建议 Boxstart 和 Nyerguds。
  • 我完全同意这些建议。更新了答案。当然,理想情况下,您应该在尝试将 textBox1.text 写入文件之前对其进行一些验证。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-02
  • 2012-09-10
  • 1970-01-01
  • 1970-01-01
  • 2012-01-24
  • 2013-11-02
  • 1970-01-01
相关资源
最近更新 更多