Pregunta

I m trying to use object handlers and I have this working fine to put stuff in memory. But when I look up the object again I return:

object(object[,]) 

or

object(double[,]) 

how do I unbox this in c#?

object(double[,]) boxedobj = ....
double[,] unboxedobj = unbox(boxedobj);

Ideally I would like to do this in a generic way so that it doesnt matter whether the tybe is double[] or double[,] or object[,], etc

¿Fue útil?

Solución

The F# unbox function is pretty much just doing cast to any other type that you specify. In C#, this could be written like this:

static R Unbox<R>(object anything) {
  return (R)anything;
}

So in your case with double[,] you'd need something like:

var array = (double[,])boxed;

In most cases unbox<'R> anything would just translate to casting using (R)anything. The only case where this does not work is when you are in another generic method and you are casting between two generic types. In that case, you need to go to object first (to make sure that the value is boxed):

static R Unbox<R, T>(T anything) {
    return (R)(object)anything;
}

Otros consejos

Unless I'm missing your point, casting to/from object should automatically box/unbox value types for you (an array is not a value type, BTW):

double d = 0.0;  // not boxed

object obj = d;  // boxed

double d2 = (double)obj;  // unboxed

The bigger question is - why do you care if its boxed or not?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top