首页 > 解决方案 > 将全局变量传递给类

问题描述

我正在尝试将字符串传递给公共类(customPanel)。

但是"teststring"永远不会传递并写入testfile.txt?
写入一个空testfile.txt字符串。

private void button1_Click(object sender, EventArgs e)
{
    customPanel cp = new customPanel();
    cp.getinfo = "teststring";
}

public class customPanel : System.Windows.Forms.Panel
{
    public String getinfo { get; set; }
    public customPanel() { InitializeComponent(); }

    private void InitializeComponent()
    {
        String gi = getinfo;

        System.IO.FileStream fs = new System.IO.FileStream("C:/folder1/testfile.txt", System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
        System.IO.StreamWriter writer = new System.IO.StreamWriter(fs);
        writer.WriteLine(gi); writer.Close(); fs.Close();
    }
}

标签: c#global-variables

解决方案


由于代码的执行顺序,您遇到的问题正在发生。

基本上,当您调用new customPanel()时,就是将调用构造函数方法controlPanel()的时候。因此,当您设置getInfo值时,您的InitializeComponent()方法已经被调用。

在不更好地了解您的上下文的情况下,简单的解决方案是将字符串作为参数传递给您的构造函数。基本上切换controlPanel()到接收 astring variableName作为参数,像这样controlPanel(string variableName),然后在调用之前InitializeComponent();用 a 设置属性的值this.getInfo = variableName;

让我知道这是否有帮助!

小心。


推荐阅读