代码之家  ›  专栏  ›  技术社区  ›  R1ZZ

具有属性的KeyValuePair可为空问题

  •  0
  • R1ZZ  · 技术社区  · 3 年前

    Code with syntax highlighting

    为什么它不允许访问Key属性,因为我在这个块中检查kvp不是null?

    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;
    }
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   Guru Stron    3 年前

    KeyValuePair 实际上 struct 所以 KeyValuePair<TKey, TValue>? 实际上 Nullable<KeyValuePair<TKey, TValue>> (见 Nullable 结构和 nullable value types Nullable.Value 得到 键值对 :

    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"