从其他类/范围获取var

时间:2016-08-31 06:04:56

标签: c# visual-studio

我只是开始使用C#,但我已经打了一堵砖墙。
我有以下内容:

public void button1_Click(object sender, EventArgs e)
{
    // Start the child process.
    Process p = new Process();
    // Redirect the output stream of the child process.
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = "C:\\Windows\\Microsoft.NET\\Framework\\v3.5\\csc.exe";
    p.StartInfo.Arguments = textBox1.Text;
    p.Start();
    // Do not wait for the child process to exit before
    // reading to the end of its redirected stream.
    // p.WaitForExit();
    // Read the output stream first and then wait.
    string output = p.StandardOutput.ReadToEnd();
    MessageBox.Show(output);

    p.WaitForExit();
}

public void label1_Click(object sender, EventArgs e)
{
    label1.Text = ;
}

如何获取output(来自public void button1_Click)并在label1中使用它?

2 个答案:

答案 0 :(得分:3)

如果这些方法都在同一个类中,请使用成员变量:

public class YourObject 
{
    private string _output;

    public void button1_Click(object sender, EventArgs args)
    {
        // ...
        _output = output;
    }

    public void label1_Click(object sender, EventArgs e)
    {
        label1.Text = _output;
    }
}

答案 1 :(得分:2)

您可以从按钮点击事件中设置label1。

public void button1_Click(object sender, EventArgs e)
    {

        // Start the child process.
        Process p = new Process();
        // Redirect the output stream of the child process.
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = "C:\\Windows\\Microsoft.NET\\Framework\\v3.5\\csc.exe";
        p.StartInfo.Arguments = textBox1.Text;
        p.Start();
        // Do not wait for the child process to exit before
        // reading to the end of its redirected stream.
        // p.WaitForExit();
        // Read the output stream first and then wait.
        label1.Text = p.StandardOutput.ReadToEnd();
        MessageBox.Show(output);

        p.WaitForExit();
    }

如果这就是你的目的