【问题标题】:KeyNotFoundException was unhandled, putting the key in the libraryKeyNotFoundException 未处理,将密钥放入库中
【发布时间】:2015-10-06 01:25:52
【问题描述】:

我正在制作一个程序,将不同的参与者放入具有特定密钥的库中。我遇到了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;
    }
}

【问题讨论】:

标签: c#


【解决方案1】:

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

因此,在您对testSessions 执行sessionPersonsSchedule[s] 之前,您可以通过调用Dictionary.ContainsKey 来确保s 首先存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 2022-06-26
    • 2013-08-06
    • 1970-01-01
    相关资源
    最近更新 更多