我现在疯了...... 我无法理解为什么如果我在事件button2_Click_2中创建变量“server”,当它按钮3_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");
}
}
}
答案 0 :(得分:4)
您正在Button2_Click_2方法中声明一个名为server的新变量。您需要将其分配给该字段,因此请更改
HttpSelfHostServer server = new HttpSelfHostServer(config);
到
server = new HttpSelfHostServer(config);
答案 1 :(得分:1)
您在两个按钮点击中都指的是server
,但实际上您没有实例化该对象。
在config
中实例化button2_Click_2
后,您还需要实例化server
:
server = new HttpSelfHostServer(config);
但如果button3_Click_1
事件在button2_Click_2
之前运行,您仍会抛出异常,因为server
仍然为空。
除非您有某种方法可以强制执行单击哪个按钮,否则您可能希望将实例化的对象移动到构造函数中,以便在引用它们时确定它们不为null。
答案 2 :(得分:1)
请注意删除var
中的局部变量声明符HttpSelfHostServer
和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");
}
}
}