变量在其他上下文c# Windows窗体中为空
本文关键字:窗体 Windows 其他 上下文 变量 | 更新日期: 2023-09-27 18:17:22
我现在要疯了…我无法理解为什么如果我在事件button2_Click_2中创建变量"服务器",当试图在事件button3_Click_1为空时访问它。
我应该怎么做才能在button3_Click_1中访问它?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using TCCWindows.Lib;
using System.Web.Http.SelfHost;
using System.Web.Http;
namespace TCCWindows
{
public partial class FormPrincipal : Form
{
HttpSelfHostServer server;
HttpSelfHostConfiguration config;
public FormPrincipal()
{
InitializeComponent();
}
private void button2_Click_2(object sender, EventArgs e)
{
var config = new HttpSelfHostConfiguration(textBox1.Text);
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
HttpSelfHostServer server = new HttpSelfHostServer(config);
server.OpenAsync();
MessageBox.Show("Server is ready!");
}
private void button3_Click_1(object sender, EventArgs e)
{
server.CloseAsync();
}
}
public class ProductsController : ApiController
{
public string GetProductsByCategory(string category)
{
return (category ?? "Vazio");
}
}
}
在Button2_Click_2方法中声明一个名为server的新变量。您需要将其分配给字段,因此更改
HttpSelfHostServer server = new HttpSelfHostServer(config);
到
server = new HttpSelfHostServer(config);
注意,在HttpSelfHostServer
中删除了局部变量声明器var
和HttpSelfHostServer
:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using TCCWindows.Lib;
using System.Web.Http.SelfHost;
using System.Web.Http;
namespace TCCWindows
{
public partial class FormPrincipal : Form
{
HttpSelfHostServer server;
HttpSelfHostConfiguration config;
public FormPrincipal()
{
InitializeComponent();
}
private void button2_Click_2(object sender, EventArgs e)
{
config = new HttpSelfHostConfiguration(textBox1.Text);
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
server = new HttpSelfHostServer(config);
server.OpenAsync();
MessageBox.Show("Server is ready!");
}
private void button3_Click_1(object sender, EventArgs e)
{
server.CloseAsync();
}
}
public class ProductsController : ApiController
{
public string GetProductsByCategory(string category)
{
return (category ?? "Vazio");
}
}
}
您在两次单击按钮时都指的是server
,但在任何时候都没有实际实例化对象。
在button2_Click_2
中实例化config
之后,您还需要实例化server
:
server = new HttpSelfHostServer(config);
但是如果button3_Click_1
事件在button2_Click_2
之前运行,你仍然会得到一个异常,因为server
仍然是空的。
除非你有办法强制哪个按钮被点击,否则你可能会想要将被实例化的对象移动到构造函数中,以便在引用它们时确保它们不是空的。