属性 的 KeyValuePair 可空问题

KeyValuePair nullable problem with property

Code with syntax highlighting

为什么不允许访问密钥 属性,因为我在这个块中检查 kvp 不为空?

public KeyValuePair<int, int>? AddRel(int from, int to)
{
    KeyValuePair<int, int>? rel = _relations
            .Where(r => r.Key == from || r.Value == to)
            .FirstOrDefault();
    if (rel != null)
    {
        _relations.Remove(rel.Key);
    }
    _relations.Add(from, to);
    return rel;
}

KeyValuePair is actually as struct, so KeyValuePair<TKey, TValue>? is actually Nullable<KeyValuePair<TKey, TValue>> (see Nullable struct and nullable value types doc) 所以你需要访问 Nullable.Value 才能得到 KeyValuePair:

if(rel.HasValue)
{
   var key = rel.Value.Key;
}

注意(感谢 @madreflection 提醒)基于 _relations FirstOrDefault 的类型可以表现 与您预期的完全不同,因为值 KeyValuePair<int,int> 的默认值不是 null:

KeyValuePair<int, int>? rel = Array.Empty<KeyValuePair<int, int>>().FirstOrDefault(); 
Console.WriteLine(rel.HasValue); // prints "True"