How to convert string to integer in C#

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

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

12条回答
  •  日久生厌
    2020-11-28 08:54

    If you are sure that you have "real" number in your string, or you are comfortable of any exception that might arise, use this.

    string s="4";
    int a=int.Parse(s);
    

    For some more control over the process, use

    string s="maybe 4";
    int a;
    if (int.TryParse(s, out a)) {
        // it's int;
    }
    else {
        // it's no int, and there's no exception;
    }
    

提交回复
热议问题