what is difference between Convert.ToInt16 and (Int16)

后端 未结 5 1287
执念已碎
执念已碎 2021-01-05 14:16

I had following piece of code

try
{
  object s = new object();
  s = 10;
  Console.WriteLine(\"{0}\", Convert.ToInt16(s));
  Console.WriteLine(\"{0}\", (In         


        
5条回答
  •  一向
    一向 (楼主)
    2021-01-05 14:59

    It depends what "s" is in your application. When you call Convert.ToInt16(s), you safely attempt to cast whatever object s is to an Int16. If "s" is previously declared as an object (object s), then it can unbox the 10 from the object. But because it is an object, you cannot explicitly cast it to an Int16, because after all, you did declare it as an object. See the code below:

    object s;
    s = new object();
    s = 10;
    Int16 newInt = (Int16)s; // This will throw, because s is actually an object
    Int16 newInt = Convert.ToInt16(s); // This will not fail, because the convert is actually holding a value of 10.
    

提交回复
热议问题