如何字符串转换为整数,在C#
问题描述:
如何将字符串转换为整数在C#?
How do I convert a string to an integer in C#?
答
如果你确定它会正确解析,用
If you're sure it'll parse correctly, use
int.Parse(string)
如果你不使用
int i;
bool success = int.TryParse(string, out i);
注意!在以下的情况下,我
将等于0,没有10后的的TryParse
。
Caution! In the case below, i
will equal 0, not 10 after the TryParse
.
int i = 10;
bool failure = int.TryParse("asdf", out i);
这是因为的TryParse
采用的出的参数,而不是一个的 REF 的参数。
This is because TryParse
uses an out parameter, not a ref parameter.