字符串到整数 [英] String to int
本文介绍了字符串到整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我可以在C#中将字符串转换为整数变量吗?如果可以,请告诉我.我给了端口号< port> 10000< port>.在xml文件中.我想从xml读取此数字并分配给int变量,以便可以将其传递给IPEndPoint()以进行客户端/服务器通信.无论我从xml读取的内容都是作为字符串检索的,我都尝试过ConvertToInt( ),但仍然无法获取.您能否解释一下原因?
Hi
can i convert a string to integer variable in C#?If so can you please tell me.I have given the port number <port>10000<port> in an xml file .I want to read this number from xml and assign to int variable so that it can be passed to the IPEndPoint() for client/server commnuication.Whatever i read from xml is retrieved as string.I tried with ConvertToInt() but still im not getting.Can you please explain me the reason?
推荐答案
int结果;
int.TryParse("10000",出结果);
int result;
int.TryParse("10000", out result);
musefan给了您完美的答案.请注意,如果不能将数字转换为int,您将得到零.
我有一个扩展方法,在处理text/xml等文件以简化内容时会用到.
musefan has given you the perfect answer. Just be aware that if the number can''t be converted to an int you will get zero.
I have an extension method that I use when working with text/xml etc files to simplify stuff.
public static class ExtensionMethods<br />{<br /> /// <span class="code-SummaryComment"><summary></span><br /> /// Converts a string to an integer.<br /> /// <span class="code-SummaryComment"></summary></span><br /> /// <span class="code-SummaryComment"><param name="value">The string to convert.</param></span><br /> /// <span class="code-SummaryComment"><returns>The integer value of the string if valid; otherwise, zero.</returns></span><br /> public static Int32 ToInt32(this string value)<br /> {<br /> int result;<br /> Int32.TryParse(value, out result);<br /> return result;<br /> }<br />}
现在我可以使用类似
int intFromFile = stringFromFile.ToInt32();
这篇关于字符串到整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文