将全局变量传递给类

时间:2019-11-19 21:28:07

标签: c# global-variables

我正在尝试将字符串传递给公共类(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();
    }
}

1 个答案:

答案 0 :(得分:1)

您遇到的问题是由于代码的执行顺序而引起的。

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

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

让我知道这是否有帮助!

保重。