如果用另一种方法声明了变量,如何在一种方法中使用变量? C# [英] How Do I Use A Variable In One Method If It Was Declared In A Different Method? C#

查看:137
本文介绍了如果用另一种方法声明了变量,如何在一种方法中使用变量? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图找出最简单的方法来重用"先前方法中的变量,但无法在任何地方准确找到我要查找的内容.

So I'm trying to figure out the easiest way to "reuse" a variable from a previous method, but cant find exactly what I'm looking for anywhere.

基本上,我有一个简单的程序,该程序使用openFileDialog打开文本文件(只需单击一次按钮即可).在另一个按钮中单击它,将我写的内容写到文件中.

Basically I have a simple program that uses openFileDialog to open a text file(this happens in one button click). In another button click it write what I wrote to the file.

我遇到的问题是写入文件,因为我无法重用方法1的path变量:/

the issue I'm Having is writing the file, because I cant reuse the path variable from method 1 :/

这是我的代码:

    public void button1_Click(object sender, EventArgs e)
    {

        OpenFileDialog OFD = new OpenFileDialog();
        OFD.Title = "Choose a Plain Text File";
        OFD.Filter = "Text File | *.txt";
        OFD.ShowDialog();
        string filePath = OFD.FileName;
        if (OFD.FileName != "") {
            using (StreamReader reader = new StreamReader(@filePath))
            {

                while (!reader.EndOfStream)
                {

                    richTextBox1.AppendText(reader.ReadLine());

                }

                reader.Close();
            }
        }
    }

    public string filePath;

    public void button2_Click(object sender, EventArgs e)
    {
        using (StreamWriter writer = new StreamWriter(@filePath)){

            writer.WriteLine(richTextBox1.Text);
            writer.Close();
        }
    }

推荐答案

public string filePath;

public void button1_Click(object sender, EventArgs e)
{

    OpenFileDialog OFD = new OpenFileDialog();
    OFD.Title = "Choose a Plain Text File";
    OFD.Filter = "Text File | *.txt";
    OFD.ShowDialog();
    filePath = OFD.FileName;
    if (OFD.FileName != "") {
        using (StreamReader reader = new StreamReader(@filePath))
        {

            while (!reader.EndOfStream)
            {

                richTextBox1.AppendText(reader.ReadLine());

            }

            reader.Close();
        }
    }
}

public void button2_Click(object sender, EventArgs e)
{
    // you should test a value of filePath (null, string.Empty)

    using (StreamWriter writer = new StreamWriter(@filePath)){

        writer.WriteLine(richTextBox1.Text);
        writer.Close();
    }
}

这篇关于如果用另一种方法声明了变量,如何在一种方法中使用变量? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆