Null propagation operator, out parameters and false compiler errors?

前端 未结 3 866
花落未央
花落未央 2020-12-09 12:17

Let\'s assume I have a class that has a property of type Dictionary, that may be null.

This compiles but the call to TryGetVa

3条回答
  •  臣服心动
    2020-12-09 12:44

    That's because if c.PossiblyNullDictionary is null, TryGetValue won't be executed and that expression won't return true or false.

    c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) returns Nullable, you can replace your code with something like this and will compile:

            string val;
            var result = c.PossiblyNullDictionary?.TryGetValue("key", out val);
            if (result.HasValue && result.Value)
            {
    
            }
    

提交回复
热议问题