How to convert string to integer in C#

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

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

12条回答
  •  伪装坚强ぢ
    2020-11-28 08:45

    int myInt = System.Convert.ToInt32(myString);
    

    As several others have mentioned, you can also use int.Parse() and int.TryParse().

    If you're certain that the string will always be an int:

    int myInt = int.Parse(myString);
    

    If you'd like to check whether string is really an int first:

    int myInt;
    bool isValid = int.TryParse(myString, out myInt); // the out keyword allows the method to essentially "return" a second value
    if (isValid)
    {
        int plusOne = myInt + 1;
    }
    

提交回复
热议问题