[英]the given key was not present in the dictionary error
the dictionary "_infoCardFactories" is defined as so: 字典“ _infoCardFactories”的定义如下:
Dictionary<string, IInfoCardFactory> _infoCardFactories;
the error "the given key was not present in the dictionary" originates from this line of code: 错误“给定的键在字典中不存在”源自此行代码:
IInfoCard card = _infoCardFactories[category].CreateNewInfoCard(category);
here is the interface for the dictionary as well the class it is implemented into. 这是字典的接口以及实现它的类。
public interface IInfoCardFactory
{
IInfoCard CreateNewInfoCard(string category);
IInfoCard CreateInfoCard(string initialDetails);
string[] CategoriesSupported { get; }
string GetDescription(string category);
}
public class creditcard : IInfoCardFactory,IInfoCard
{
public IInfoCard CreateNewInfoCard(string category)
{
creditcard card = new creditcard();
return card;
}
}
i cannot show all of the code, due the fact this is an assigment however i would be greatful if someone could help me out. 我不能显示所有代码,由于这是一个事实,但是如果有人可以帮助我,我将非常感激。
You need to implement a class based on this interface and then define your dictionary to use that implementation. 您需要基于此接口实现一个类,然后定义字典以使用该实现。 There needs to be an instance.
需要有一个实例。
Instead of IInfoCard card = _infoCardFactories[category].CreateNewInfoCard(category);
代替
IInfoCard card = _infoCardFactories[category].CreateNewInfoCard(category);
Use this: 用这个:
IInfoCard card;
IInfoCardFactory factory;
if (_infoCardFactories.TryGetValue(category, out factory))
card = factory.CreateNewInfoCard(category);
else
{
// when category is not in your dictionary
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.