帶有語法高亮的代碼
為什么它不允許訪問 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;
}
uj5u.com熱心網友回復:
KeyValuePair實際上是 as struct,實際上也是如此 KeyValuePair<TKey, TValue>?(Nullable<KeyValuePair<TKey, TValue>>參見Nullablestruct and nullable value types doc),因此您需要訪問Nullable.Valueget KeyValuePair:
if(rel.HasValue)
{
var key = rel.Value.Key;
}
注意(感謝@madreflection提醒)基于型別的_relations FirstOrDefault行為可能與您所期望的完全不同,因為 value 的默認值KeyValuePair<int,int>is not null:
KeyValuePair<int, int>? rel = Array.Empty<KeyValuePair<int, int>>().FirstOrDefault();
Console.WriteLine(rel.HasValue); // prints "True"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/460847.html
