what is difference between Convert.ToInt16 and (Int16)

后端 未结 5 1177
执念已碎
执念已碎 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:55

    In the problem line you are attempting to cast something that is not Int16 (probably Int32?) into the Int16 type. If you change the assignment to this I bet it will work (ideone):

    object s, s2;
    s = Convert.ToInt16(10);
    s2 = 10;
    Console.WriteLine("Types: {0} and {1}", s.GetType(), s2.GetType());
    Console.WriteLine("s as Int16 (works): {0}", (Int16)s);
    Console.WriteLine("s2 as Int16 (error): {0}", (Int16)s2);
    

    Output:

    Runtime error    time: 0.03 memory: 36592 signal:-1
    Types: System.Int16 and System.Int32
    s as Int16 (works): 10
    

    From the comments, casting Int32 to Int16 directly works becasue the compiler knows they can be converted and does that automatically. When you are working with a bare object though it is going blind and will not automatically convert. This will work for instance:

        Console.WriteLine("s2 as Int16 (works): {0}", (Int16)((Int32)s2));
    

提交回复
热议问题