2011-07-10 60 views
0

所以我想弄清楚从先前的方法“重用”一个变量的最简单的方法,但无法找到我正在寻找什么地方。如何以一种方法使用变量?如果使用其他方法声明该变量? 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(); 
     } 
    } 
+0

如果您接受答案,它将是n冰。 –

回答

1

使它成为一个实例变量。

string path = ""; 

public void FirstMethod() 
{ 
    path = "something"; 
} 

public void SecondMethod() 
{ 
    doSomething(path); 
} 
1
在你的方法

只是删除声明字符串文件路径,使其看起来像

filePath = OFD.FileName; 

,这是所有

+0

谢谢你的工作!但你能解释一下为什么这项工作? – Kriptonyc

+0

你已经声明了与类成员同名的局部变量,所以当你在方法中设置'filePath'时,你只需要设置本地'filePath'而不是你的类成员'filePath'。在内部作用域(你的button1_Click方法)中使用相同类型和名称声明的变量总是将它们从外部作用域(在这种情况下是你的类)隐藏起来。 – grapkulec

0

你不能在你的代码已经发布,因为它的出范围消失了。

您可以让第一个方法返回选择,然后将其传递给第二个方法。这将工作。

我不喜欢你的方法名称。 button2_Clickbutton1_Click?他们都没有告诉客户该方法做了什么。

你的方法可能做得太多。我可能有一种方法来选择文件并单独读取和写入。

1
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(); 
    } 
} 
0

filePath串中的的button1_Click声明一个string的一个新实例,其中HIES成员实例一个范围。删除string类型以使方法中的filePath引用成员实例。很可能你也不需要emmeber实例为public,但应该是私有的,因为它允许两种方法进行通信。

public void button1_Click(object sender, EventArgs e) 
    { 
     // etc. 
     filePath = OFD.FileName; 
    } 

private string filePath; 
相关问题