当我将数据放入函数=>中的类的公共实例时,我遇到了一个问题;
static async Task _MainAsync()
{
Form1 info = new Form1();
info.decoded = JsonConvert.DeserializeObject<Rootobject>(msg);
}// the code is simplified
当我在另一个函数中使用它时,类的实例变为null,我该如何修复它?
private async void button1_Click(object sender, EventArgs e)
{
await _MainAsync();
coin.Text = decoded.message;
}
您在_MainAsync()
中创建的实例Form1 info = new Form1();
是本地的。您无法从方法外部访问它。更改其属性的一种方法是在button1_Click
中创建实例,将该实例作为方法参数发送到_MainAsync()
。更改其中的属性并继续在button1_Click
中工作。
static async Task _MainAsync(Form1 form1Instance)
{
...
form1Instance.decoded = JsonConvert.DeserializeObject<Rootobject>(msg);
...
}
private async void button1_Click(object sender, EventArgs e)
{
...
Form1 info = new Form1();
await _MainAsync(info);
coin.Text = info.decoded.message;
...
}