C# 无法将类型“string”隐式转换为“int”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11274555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot implicitly convert type 'string' to 'int'
提问by user1493065
I keep getting the debug error "cannot implicitly convert type 'string' to 'int'" in C#.
我一直在 C# 中收到调试错误“无法将类型‘string’隐式转换为‘int’”。
Here is a snippet of my code:
这是我的代码片段:
private void button2_Click(object sender, EventArgs e) //button to start takedown
{
byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes("<Packet OF Data Here>");
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);
}
回答by Ashwin Singh
Here is the error:
这是错误:
int port = "80";
convert it into
将其转换为
int port=80;
回答by Zbigniew
You have to convert stringto inthere:
你必须转换string到int这里:
int port = "80"; // can't assign string to int
Just pass it as int:
只需将其作为 int 传递:
int port = 80;
回答by keyboardP
int port = "80";
is incorrect because intexpected an integer, not a string. By using speech marks, you're provding 80as a string, not as a integer. Simply remove the speech marks so that you're assigning the variable as an integer.
不正确,因为int需要一个整数,而不是一个字符串。通过使用语音标记,您可以80作为字符串而不是整数来证明。只需删除语音标记,以便将变量分配为整数。
int port = 80;
回答by selbie
In your case, everyone else's answer that port needs to be of type "int" instead of type "string" is correct. However, if you really had a string from user input, and you needed to convert it back into an int Int32.TryParseor Int32.Parsewill suffice.
在你的情况下,其他人的答案是端口需要是“int”类型而不是“string”类型是正确的。但是,如果您确实有来自用户输入的字符串,并且您需要将其转换回 int Int32.TryParse或Int32.Parse就足够了。
回答by Jenninha
If possible:
如果可能的话:
int port = 80;
If you cannot have an int variable you will have to parse it:
如果你不能有一个 int 变量,你将不得不解析它:
int port = Int32.Parse("80");
e.g.
例如
string a = "80";
int port = Int32.Parse(a);
回答by Learning
You can't mention integer in "" as you have done int port = "80";
你不能像你所做的那样在“”中提到整数 int port = "80";
correct version should be int port = 80;
正确的版本应该是 int port = 80;
回答by Bala
change
int port = "80";
to
varport = "80";
更改
int 端口 = "80";
到
var端口 = "80";
And
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);
to
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), Convert.ToInt32(port));
和
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);
到
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), Convert.ToInt32(port));

