System.Convert.ToInt vs (int)

前端 未结 4 1648
猫巷女王i
猫巷女王i 2020-12-18 22:38

I noticed in another post, someone had done something like:

double d = 3.1415;
int i = Convert.ToInt32(Math.Floor(d));

Why did they use the

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-18 23:19

    You can use Convert when you have a string that you want to convert to an int

    int i = Convert.ToInt32("1234");
    

    Convert and casting will both throw an exception if they fail.

    i.e, this will still throw an exception, it will not return 0:

    Convert.ToInt32("1234NonNumber");
    

    In many cases Convert and casting will have the same result, but a cast is often times easier to read.

提交回复
热议问题