¿Cómo desempaquetar una matriz de cadenas?

Suppose I have an array of string boxed to an object:

string[] files = Directory.GetFiles(path);
object obj = files;

How can I unboxed the files into array of string again?

preguntado el 01 de febrero de 12 a las 04:02

Beware your wording: strings do not "box." What you have done is implicitly convert the string array to object, but no boxing is involved, nor is any unboxing. To clarify, boxing and unboxing are terms used when value types are converted to and from reference types. System.String is not a value type. -

Continued: An array of strings is also not a value type, nor is an array of cualquier cosa a value type. The terms you'd want to use are emitir y la convertir. -

3 Respuestas

El operador as es como una conversión, excepto que produce un valor nulo en caso de error de conversión en lugar de generar una excepción. Como operador

string[] someVarArray = obj as string[] 
if(someVarArray!=null)
{
 //do something
}

Respondido 01 Feb 12, 08:02

Lo que necesita es un emitir, not boxing and unboxing.

string[] files2 = (string[])obj;

But be aware, do this if you are sure that your object contains an array of strings (string[]), or otherwise you get an InvalidCastException. If you are not sure, you have two ways to test the object:

string[] files2;
if( o is string[] )
{
    files2 = (string[])o;
    // do whatever with files2
}

or

string[] files2 = o as string[];
if( files2 != null )
{
    // do whatever with files2
}

respondido 24 mar '12, 16:03

you could use the as operator..

if ( obj is string[])
    string[] files = obj as string[];

you could just "cast" it back....

if ( obj is string[])
    string[] files = (string[])obj;

Respondido 01 Feb 12, 08:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.