How to convert string to integer in C#

前端 未结 12 1521
我在风中等你
我在风中等你 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;
    }
    
    0 讨论(0)
  • 2020-11-28 08:47
    int a = int.Parse(myString);
    

    or better yet, look into int.TryParse(string)

    0 讨论(0)
  • 2020-11-28 08:50
    int i;
    
    string result = Something;
    
    i = Convert.ToInt32(result);
    
    0 讨论(0)
  • 2020-11-28 08:53
    class MyMath
    {
        public dynamic Sum(dynamic x, dynamic y)
        {
            return (x+y);
        }
    }
    
    class Demo
    {
        static void Main(string[] args)
        {
            MyMath d = new MyMath();
            Console.WriteLine(d.Sum(23.2, 32.2));
        }
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-11-28 08:58

    You can use either,

        int i = Convert.ToInt32(myString);
    

    or

        int i =int.Parse(myString);
    
    0 讨论(0)
提交回复
热议问题