2009-08-14 7 views
59

Duplicar posibles:
Nullable types and the ternary operator: why is `? 10 : null` forbidden?El código C# no se compilará. Sin conversión implícita entre nulo y int

Por qué no funciona? Parece un código válido.

string cert = ddCovCert.SelectedValue; 
    int? x = (string.IsNullOrEmpty(cert)) ? null: int.Parse(cert); 
    Display(x); 

¿Cómo debo codificar esto? El método toma un Nullable. Si el desplegable tiene una cadena seleccionada, necesito analizar eso en un int; de lo contrario, quiero pasar nulo al método.

+4

Duplicar (int?) - consulte http://stackoverflow.com/questions/858080/nullable-types-and-the-ternary-operator-why-wont-this-work –

+1

También para obtener más información, consulte http://stackoverflow.com/questions/220250/in-c-why-cant-a- conditional-operator-impliedly-cast-to-a-nullable-type –

Respuesta

195
int? x = string.IsNullOrEmpty(cert) ? (int?)null : int.Parse(cert); 
+0

beautiful. ¡Gracias! – Hcabnettek

+0

A veces lo necesito, pero siempre lo olvido y termino aquí: D. Gracias – Steven

+0

Ahorré mi tiempo. Gracias . –

7

me he encontrado con lo mismo ... por lo general sólo tire la nula a

int? x = (string.IsNullOrEmpty(cert)) ? (int?)null: int.Parse(cert); 
Cuestiones relacionadas