How can I quickly up-cast object[,] into double[,]?

后端 未结 5 797
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 14:19

I using Microsoft.Office.Interop.Excel I get returned a 2D array of type object[,] which contains double for elements. Note that the i

5条回答
  •  星月不相逢
    2020-11-28 15:16

    There are a couple problems here.

    First, since double is not a reference type it must be boxed to be stored in an object[], so the only way to get to the values is to unbox the values into a double[] (copy copy).

    The other problem is that in C#, arrays are covariant but not contravariant, you can assign an array to a reference of a more-derived type, not not to one of a less-derived type.

    string[] strings = new string[10];
    object[] objects = strings; // OK, covariant
    string[] strings2 = objects; // not OK, contravariant
    objects[0] = 10; // Compiles fine, runtime ArrayTypeMismatchException!
    

提交回复
热议问题