C# if-null-then-null expression

前端 未结 6 1931
误落风尘
误落风尘 2020-12-01 02:56

Just for curiosity/convenience: C# provides two cool conditional expression features I know of:

string trimmed = (input == null) ? null : input.Trim();
         


        
6条回答
  •  遥遥无期
    2020-12-01 03:16

    You can choose between a custom Nullify class or a NullSafe extension method as described here: http://qualityofdata.com/2011/01/27/nullsafe-dereference-operator-in-c/

    The usage will be as follows:

    //Groovy:
    bossName = Employee?.Supervisor?.Manager?.Boss?.Name
    
    //C# Option 1:
    bossName = Nullify.Get(Employee, e => e.Supervisor, s => s.Manager,
                           m => m.Boss, b => b.Name);
    //C# Option 2:
    bossName = Employee.NullSafe( e => e.Supervisor ).NullSafe( s => s.Boss )
                          .NullSafe( b => b.Name );
    

提交回复
热议问题