what is difference between Convert.ToInt16 and (Int16)

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

    A boxed value type instance during unpacking, you should note the following:

    1. Included on the boxed value type instance is null, throws a NullReferenceException exception.

    2. If the reference point of the object is not required a boxed value type instance throws an InvalidCastException exception.

    The second means that the following code does not work properly:

    s = new object();
    s = 10;
    Console.WriteLine("{0}", Convert.ToInt16(s));
    Console.WriteLine("{0}", (Int16)s);//throws an InvalidCastException exception
    

    The logic can obtain s referenced by a boxed Int32, and its transformation into a INT6. Unboxing operations on an object can only be transformed into unboxed value type, in this case is Int32. Here is the correct wording:

    The below line solves your Issue

    Console.WriteLine("{0}", (Int16)(int)s); / / first unboxing of the correct type, and then transition 
    

提交回复
热议问题