[英]How Do I Use A Variable In One Method If It Was Declared In A Different Method? C#
因此,我试图找出从以前的方法中“重用”变量的最简单方法,但在任何地方都找不到我正在寻找的东西。
基本上我有一个简单的程序,它使用 openFileDialog 打开一个文本文件(这发生在一个按钮单击中)。 在另一个按钮中单击它,将我写的内容写入文件。
我遇到的问题是编写文件,因为我无法重用方法 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();
}
}
使其成为实例变量。
string path = "";
public void FirstMethod()
{
path = "something";
}
public void SecondMethod()
{
doSomething(path);
}
在您的方法中,只需删除声明字符串 filePath 使其看起来像
filePath = OFD.FileName;
这就是全部
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();
}
}
你不能在你发布的代码中,因为它已经超出了 scope 并且消失了。
您可以让第一个方法返回选择,然后将其传递给第二个方法。 那会奏效。
我不喜欢你的方法名称。 button2_Click
? button1_Click
? 两者都没有告诉客户该方法的作用。
你的方法可能做得太多了。 我可能有一种方法来选择文件并单独读取和写入。
button1_Click 中的filePath
字符串声明了一个新的string
实例,在 scope 中,它包含成员实例。 删除string
类型以使方法中的filePath
引用成员实例。 很可能您也不需要将 emmeber 实例设为public
,但应该是私有的,因为它允许这两种方法进行通信。
public void button1_Click(object sender, EventArgs e)
{
// etc.
filePath = OFD.FileName;
}
private string filePath;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.