无法将类型’string’隐式转换为’int’

我一直得到调试错误“不能在C#中隐式地将类型’字符串’转换为’int’”。

这是我的代码片段:

private void button2_Click(object sender, EventArgs e) //button to start takedown { byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes(""); string IP = "127.0.0.1"; int port = "80"; IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); client.SendTo(packetData, ep); } 

这是错误:

 int port = "80"; 

把它转换成

 int port=80; 

如果可能的话:

 int port = 80; 

如果你不能有一个int变量,你将不得不解析它:

 int port = Int32.Parse("80"); 

例如

 string a = "80"; int port = Int32.Parse(a); 

你必须在这里将string转换为int

 int port = "80"; // can't assign string to int 

只需将其作为int传递:

 int port = 80; 

在你的情况下,其他人的答案是端口需要是“int”类型而不是类型“string”是正确的。 但是,如果你真的有一个来自用户输入的字符串,你需要将它转换回int Int32.TryParse或Int32.Parse就足够了。

 int port = "80"; 

是不正确的,因为int期望整数,而不是字符串。 通过使用语音标记,您将80作为字符串,而不是整数。 只需删除语音标记,以便将变量指定为整数。

 int port = 80; 

你不能在“”中提到整数,因为你已经完成了int port = "80";

正确的版本应该是int port = 80;

更改
int port =“80”;

var port =“80”;


IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP),port);

IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), Convert.ToInt32(port) );