2010-06-07 15 views
6

En C# 4, no estaba allí, una simplificación de la comprobación de valores nulos, así:C# 4: ¿cómo detectar nulls en línea?

if(myobject?.myproperty?.myotherproperty?.value != null) 

El valor volvería nulo y no una excepción.

¿Alguien tiene un enlace a cómo usarlo o al menos la sintaxis?

+0

Relacionados http://stackoverflow.com/questions/2929836 –

Respuesta

9

Este operador se llama safe navigation operator en Groovy.

No está disponible en C#, sin embargo, ni siquiera en C# 4.

Si suficientes personas muestran su apoyo a la misma, tal vez va a entrar en una versión futura hipotética de C# ...

+0

Creo que esta es una de las nuevas características en C# 6 http://msdn.microsoft.com/en-us/magazine/dn802602.aspx – user65439

1

En C#/C++, puedo lograr esto usando el operador ternario aunque el código sería horrible. ¿Estás seguro de que quieres usar esto?

if ((MyObject = null (myObject.myProperty = null (myobject.myproperty.myotherproperty = null myobject.myproperty.myotherproperty.value:!?!?!? Null): null): null) = nula)

class MyOtherProperty 
{ 
    public string value; 
} 

class MyProperty 
{ 
    public MyOtherProperty myotherproperty; 
} 

class MyObject 
{ 
    public MyProperty myproperty; 
} 

Mi Unidad código de prueba:

[TestMethod()] 
    public void TestTernaryOperator() 
    { 
     MyObject myobject = new MyObject(); 
     Debug.WriteLine (string.Format ("{0}, {1}", myobject != null, myobject.myproperty != null)); 
     Debug.WriteLine(string.Format("IsNotNull = {0}", IsNotNull(myobject))); 
     myobject.myproperty = new MyProperty(); 
     Debug.WriteLine (string.Format ("{0}, {1}, {2}", myobject != null, myobject.myproperty != null, myobject.myproperty.myotherproperty != null)); 
     Debug.WriteLine(string.Format("IsNotNull = {0}", IsNotNull(myobject))); 
     myobject.myproperty.myotherproperty = new MyOtherProperty(); 
     Debug.WriteLine (string.Format ("{0}, {1}, {2}, {3}", myobject != null, myobject.myproperty != null, myobject.myproperty.myotherproperty != null, myobject.myproperty.myotherproperty.value != null)); 
     Debug.WriteLine(string.Format("IsNotNull = {0}", IsNotNull(myobject))); 
     myobject.myproperty.myotherproperty.value = "Hello world"; 
     Debug.WriteLine(string.Format("{0}, {1}, {2}, {3}", myobject != null, myobject.myproperty != null, myobject.myproperty.myotherproperty != null, myobject.myproperty.myotherproperty.value != null)); 
     Debug.WriteLine(string.Format("IsNotNull = {0}", IsNotNull(myobject))); 

    } 

    bool IsNotNull(MyObject myobject) 
    { 
     bool isNotNull = (myobject != null ? (myobject.myproperty != null ? (myobject.myproperty.myotherproperty != null ? myobject.myproperty.myotherproperty.value : null) : null) : null) != null; 
     return isNotNull; 
    } 
+0

Soy un chico viejo de Unix yc, así que en realidad prefiero este enfoque sobre el if (this == null) y luego si (thisOtherThing == null) etc. –

2

Como otros han dicho, no hay construido en forma de hacerlo en C#. Hace unos meses, escribí un blog post en una manera de hacer que el uso de expresiones, con un método NullSafeEval extensión:

if (myobject.NullSafeEval(o => o.myproperty.myotherproperty.value) != null) 
... 

pero es sólo una prueba de concepto, no he probado a fondo, y es bastante lento ...

2

En C# también hay ?? operador que se utiliza para probar contra nulo. Esto es un poco mejor que? operador.

(x ?? -1) es equivalente a (x = null x:? -1)

+0

también conocido como el "operador coalescente nulo". una de las pocas palabras clave usadas. – Syd

Cuestiones relacionadas