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

后端 未结 12 1061
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  庸人自扰
    2020-12-04 19:34

    public class ok {
        T s;
        public static implicit operator ok(T s) { return new ok { s = s }; }
        public static implicit operator T(ok _) { return _.s; }
    
        public static bool operator true(ok _) { return _.s != null; }
        public static bool operator false(ok _) { return _.s == null; }
        public static ok operator &(ok x, ok y) { return y; }
    }
    

    I often need this logic for strings:

    using ok = ok;
    
    ...
    
    string bob = null;
    string joe = "joe";
    
    string name = (ok)bob && bob.ToUpper();   // name == null, no error thrown
    string boss = (ok)joe && joe.ToUpper();   // boss == "JOE"
    

提交回复
热议问题