Is there an “opposite” to the null coalescing operator? (…in any language?)

后端 未结 12 1077
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 18:38

null coalescing translates roughly to return x, unless it is null, in which case return y

I often need return null if x is null, otherwise return x

12条回答
  •  旧时难觅i
    2020-12-04 19:07

    PowerShell let's you reference properties (but not call methods) on a null reference and it will return null if the instance is null. You can do this at any depth. I had hoped that C# 4's dynamic feature would support this but it does not.

    $x = $null
    $result = $x.y  # $result is null
    
    $x = New-Object PSObject
    $x | Add-Member NoteProperty y 'test'
    $result = $x.y  # $result is 'test'
    

    It's not pretty but you could add an extension method that will function the way you describe.

    public static TResult SafeGet(this T obj, Func selector) {
        if (obj == null) { return default(TResult); }
        else { return selector(obj); }
    }
    
    var myClass = new MyClass();
    var result = myClass.SafeGet(x=>x.SomeProp);
    

提交回复
热议问题