C#怎么调用类里面的代码?
有一个类“”Program“publicclassProgram{boolapple=true;stringoutput="";Socketsocket;publicvo...
有一个类“”Program“
public class Program
{
bool apple=true;
string output="";
Socket socket;
public void startServer()
{
//本机IP
IPAddress ip = IPAddress.Parse("192.168.1.113");
//IP地址跟端口的组合
IPEndPoint iep = new IPEndPoint(ip, 10086);
//创建Socket
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定Socket
socket.Bind(iep);
//服务器已经做好接收任何连接的准备
socket.Listen(10);
}
public string receiveText()
{
while (true)
{
//执行accept方法
Socket Client =socket.Accept();
byte[] message = new byte[1024];
NetworkStream networkStream = new NetworkStream(Client);
int len = networkStream.Read(message, 0, message.Length);
//byte数组转换成string
output = System.Text.Encoding.Unicode.GetString(message);
return output;
}
}
}
然后按钮的运行函数是
private void button2_Click(object sender, EventArgs e)
{
Program Server = new Program();
Server.receiveText();
textBox1.Text = Server.receiveText();
}
按下这个按钮后会提示错误:未将对象引用设置到对象的实例
请问是不是因为前面的声明变量没有运行? 展开
public class Program
{
bool apple=true;
string output="";
Socket socket;
public void startServer()
{
//本机IP
IPAddress ip = IPAddress.Parse("192.168.1.113");
//IP地址跟端口的组合
IPEndPoint iep = new IPEndPoint(ip, 10086);
//创建Socket
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定Socket
socket.Bind(iep);
//服务器已经做好接收任何连接的准备
socket.Listen(10);
}
public string receiveText()
{
while (true)
{
//执行accept方法
Socket Client =socket.Accept();
byte[] message = new byte[1024];
NetworkStream networkStream = new NetworkStream(Client);
int len = networkStream.Read(message, 0, message.Length);
//byte数组转换成string
output = System.Text.Encoding.Unicode.GetString(message);
return output;
}
}
}
然后按钮的运行函数是
private void button2_Click(object sender, EventArgs e)
{
Program Server = new Program();
Server.receiveText();
textBox1.Text = Server.receiveText();
}
按下这个按钮后会提示错误:未将对象引用设置到对象的实例
请问是不是因为前面的声明变量没有运行? 展开
展开全部
你按钮里的
Server.receiveText();
该是
Server.startServer();
吧,都没启动Server就打算收了?什么都没初始化呢。
Server.receiveText();
该是
Server.startServer();
吧,都没启动Server就打算收了?什么都没初始化呢。
更多追问追答
追问
不是,你没看到是button2吗。。。
前面还有个private void button1_Click(object sender, EventArgs e)
{
Program Server = new Program();
Server.startServer();
}
追答
你不说谁知道你还有个button1。
其次,button1里的Program Server = new Program();和button2里的Program Server = new Program();无关,Server在button2里又一次创建一个新的实例,还是没有startServer。应该把button1里的移到button2里去
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询