我想用C#制作一个简单的TCP服务器,所以我想定义一些变量,但我无法访问我声明的变量。是否有可能绕过这一点?
当前代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace TCP_Server_gui
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string serverIp = "127.0.0.1";
int serverPort = 4200;
IPAddress localAdd = IPAddress.Parse(serverIp);
TcpListener listener = new TcpListener(localAdd, serverPort);
}
}
我收到这些错误:
Severity Code Description
Error CS0236 A field initializer cannot reference the non-static field, method, or property 'Form1.serverIp'
Error CS0236 A field initializer cannot reference the non-static field, method, or property 'Form1.localAdd'
Error CS0236 A field initializer cannot reference the non-static field, method, or property 'Form1.serverPort'
C# 是一种严格的面向对象语言(对于 OOP :P 的特定定义),因此没有 C 样式变量。相反,您有字段和局部变量。
在您的例子中,您已经声明了多个字段。但是,字段(与 C 样式变量和 C# 的局部变量不同)没有定义的执行顺序,因此它们的初始值设定项不能相互引用。相反,您需要将初始值设定项移动到构造函数:
public Form1()
{
InitializeComponent();
localAdd = IPAddress.Parse(serverIp);
listener = new TcpListener(localAdd, serverPort)
}
string serverIp = "127.0.0.1";
int serverPort = 4;
IPAddress localAdd;
TcpListener listener;
将非常量初始值设定项放在构造函数中:
public Form1()
{
InitializeComponent();
localAdd = IPAddress.Parse(serverIp);
listener = new TcpListener(localAdd, serverPort);
}
string serverIp = "127.0.0.1";
int serverPort = 4200;
IPAddress localAdd;
TcpListener listener;
}
原因是无法保证字段初始值设定项按任何特定顺序运行,因此无法保证在运行IPAddress
的初始值设定项时将初始化serverIp
。 如果将它们放在构造函数中,则可以控制顺序。
您必须在表单构造函数中调用您的方法:
public partial class Form1 : Form
{
string serverIp = "127.0.0.1";
int serverPort = 4200;
public Form1()
{
InitializeComponent();
IPAddress localAdd = IPAddress.Parse(serverIp);
TcpListener listener = new TcpListener(localAdd, serverPort);
}
}
如果您希望在类中全局访问localAdd
和listener
,则必须将它们移到构造函数之外:
public partial class Form1 : Form
{
string serverIp = "127.0.0.1";
int serverPort = 4200;
IPAddress localAdd;
TcpListener listener;
public Form1()
{
InitializeComponent();
localAdd = IPAddress.Parse(serverIp);
listener = new TcpListener(localAdd, serverPort);
}
}