且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中将字符串转换为整数

更新时间:2023-02-03 08:37:55

如果你确定它会正确解析,使用

If you're sure it'll parse correctly, use

int.Parse(string)

如果不是,请使用

int i;
bool success = int.TryParse(string, out i);

注意!在以下情况下,i 将等于 0,而不是 TryParse 之后的 10.

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 使用 out 参数,而不是 ref 参数.

This is because TryParse uses an out parameter, not a ref parameter.