KeyNotFoundException未处理,将密钥放入库中

本文关键字:密钥 未处理 KeyNotFoundException | 更新日期: 2023-09-27 18:16:10

我正在编写一个程序,该程序将不同的参与者放入具有特定密钥的库中。我遇到了一个问题,我得到了一个KeyNotFoundException

这里你可以看到我的代码错误在if (sessionPersonsSchedule[s].Count == s.MaxParticipants)

public bool personAddToLibrary(int personsIn)
{   
    if (personsIn == participants.Count)
    {
        return true;
    }
    else
    {
        for ( int j = 0; j < participants[personsIn].Preferences.Count; j++ )
        {
            Participant p = participants[personsIn];
            Session s = sessions[p.Preferences[j] - 1];
            SessionPersonsSchedule[s]
            if (testSessions(s))
            {
                sessionPersonsSchedule[s].Add(p);
                Console.Write(personsIn + ". " + p + "is added to session " + s);
                personAddToLibrary(personsIn + 1);
                if (personsIn == participants.Count)
                {
                    return true;
                }
            }
            else
            {
                sessionPersonsSchedule[s].Remove(p);
                Console.Write(personsIn + ". " + p + "is deleted from session " + s);
            }
        }
    }
    return false;
}
public bool testSessions(Session s)
{
    if (sessionPersonsSchedule[s].Count == s.MaxParticipants)
    {
        return false;
    }
    else
    {
        return true;
    }
}

KeyNotFoundException未处理,将密钥放入库中

KeyNotFoundException表示您正在尝试使用集合中不存在的键索引到集合。

因此,在testSessions中执行sessionPersonsSchedule[s]之前,您可以通过调用Dictionary.ContainsKey.

确保s首先存在。