How to convert string to integer in C#

前端 未结 12 1667
我在风中等你
我在风中等你 2020-11-28 08:17

How do I convert a string to an integer in C#?

12条回答
  •  青春惊慌失措
    2020-11-28 09:05

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

    int.Parse(string)
    

    If you're not, use

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

    Caution! In the case below, i will equal 0, not 10 after the TryParse.

    int i = 10;
    bool failure = int.TryParse("asdf", out i);
    

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

提交回复
热议问题