c# - 将全局变量传递给类
问题描述
我正在尝试将字符串传递给公共类(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();
}
}
解决方案
由于代码的执行顺序,您遇到的问题正在发生。
基本上,当您调用new customPanel()
时,就是将调用构造函数方法controlPanel()
的时候。因此,当您设置getInfo
值时,您的InitializeComponent()
方法已经被调用。
在不更好地了解您的上下文的情况下,简单的解决方案是将字符串作为参数传递给您的构造函数。基本上切换controlPanel()
到接收 astring variableName
作为参数,像这样controlPanel(string variableName)
,然后在调用之前InitializeComponent();
用 a 设置属性的值this.getInfo = variableName;
。
让我知道这是否有帮助!
小心。
推荐阅读
- c++ - C ++无法通过膨胀算法解压缩从WebSocket API(Okex)返回的消息
- asp.net - 登录后页面重新加载,而不是重定向到另一个页面
- postgresql - 选择前 x% 的记录
- javascript - Having problems reassigning a variable
- javascript - 加载 UTF-8 文本或 html 文件并使用 JavaScript 将其添加到 dom
- google-cloud-platform - 带有 Google IDP 的 GCP 身份平台
- node.js - Reactjs Redux 优化最佳实践
- reactjs - 如何修复 Creative Tim 材料设计仪表板图表与材料 UI 动画的不完整显示?(增长,幻灯片等_
- reactjs - 有没有办法在 React 中使用 MathJax v3?
- python - 如何在不使用 tf.keras.layers.conv2d 的情况下计算 tf.nn.conv2d 的反向传播