C# if-null-then-null expression

前端 未结 6 1934
误落风尘
误落风尘 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条回答
  •  Happy的楠姐
    2020-12-01 03:03

    As a workaround you can use this which is based on Maybe monad.

    public static Tout IfNotNull(this Tin instance, Func Output)
    {
        if (instance == null)
            return default(Tout);
        else
            return Output(instance);
    }
    

    Use it this way:

    int result = objectInstance.IfNotNull(r => 5);
    var result = objectInstance.IfNotNull(r => r.DoSomething());
    

提交回复
热议问题