如何从不同的函数中调用字符串

本文关键字:函数 调用 字符串 | 更新日期: 2023-09-27 18:11:20

调用字符串"rlist"时遇到麻烦:
        public void main()
    {
        string rlist;
        if (radioButton1.Checked)
            textBox1.Enabled = false;
        textBox1.ReadOnly = true;
        rlist = "text";
    }

        public void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFile = new OpenFileDialog();
        openFile.Filter = "WTF Files (*.wtf)|*.wtf";
        openFile.Title = "Please Pick your realmlist file:";
        if (openFile.ShowDialog() == DialogResult.Cancel)
            return;
        try
        {
            textBox5.Text = openFile.FileName;
            string file = openFile.FileName;
            TextWriter rlist_writer = new StreamWriter (openFile.FileName);
            rlist_writer.WriteLine(rlist);
            rlist_writer.Close();
        }
        catch (Exception)
        {
            MessageBox.Show("Error opening file", "File Error",
            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }

我得到了这一行的错误:

rlist_writer.WriteLine(rlist);

是否有可能从一个函数中调用字符串,并将其发送给另一个函数,其值与最初从函数中提取的值相同?

如何从不同的函数中调用字符串

听起来你的问题,

您的字符串是您的main函数的局部。因此,根据您的方法名称和winforms知识判断(再次假定)你需要让你的字符串class level

string rlist;
public void main()
{
rlist = "yay"
public void button1_Click(object sender, EventArgs e)
{
someText = rlist;

就目前情况而言,您不能这样做,因为当您离开

方法时,临时(局部)变量将通过垃圾收集被清除。

编辑

你不妨也看看这个

   try
    {
        textBox5.Text = openFile.FileName;
        using(TextWriter rlist_writer = new StreamWriter (openFile.FileName))
        {
            rlist_writer.WriteLine(rlist);
        }
    }

您可以在类作用域中定义该变量,然后如果在button_click事件中调用该变量,它将保持与主方法中相同的值。