学生在这里。
正在处理当前的 C# 项目。我必须创建一个 List< Card > 的扑克牌,和一个 Dictionary< string,List< Card >>。
列表是独立创建的,字典包含卡片的集合。可以在集合中添加或删除卡片。
不过,我在将卡片添加到收藏夹时遇到了问题。我已经从用户输入中获得了列表的索引号,并试图根据索引简单地更新字典中的值。
抛出错误的行在这里。错误是 无法将类型“< filename.CardClass >”隐式转换为 System.Collections.Generic.List< filename.CardClass >'
我这辈子都搞不懂这意味着什么以及如何解决它..
_collections[input] = _cards[cardSelectionIndex];
这是我当前的代码块:
public void AddToCollection()
{
PrintValuesCollections<string, List<Card>>(_collections);
Console.WriteLine("Type in the name of the collection to add a card to:");
string input = Console.ReadLine();
bool found = _collections.ContainsKey(input);
if (found)
{
Console.WriteLine("List of current cards to choose from:");
for (int i = 0; i < _cards.Count; i++)
{
Console.WriteLine("Index number:\r\n"+i+"Card Info:\r\n"+_cards[i]+"\n");
}
Console.WriteLine("Type in the index of the card from the list to add to the collection:");
string cardSelection = Console.ReadLine();
int cardSelectionIndex = 0;
while (!int.TryParse(cardSelection, out cardSelectionIndex))
{
Console.Write("Please enter a number from the list above: ");
input = Console.ReadLine();
}
_collections[input] = _cards[cardSelectionIndex];
_cards.RemoveAt(cardSelectionIndex);
}
else
Console.WriteLine("Collection name not found.");
}
最佳答案
我假设 _collections
类型是 Dictionary<string, List<Card>>
和 _cards
是 List<Card>
所以这就是您要尝试做的:
//_collections[input] = _cards[cardSelectionIndex];
List<Card> a = _collections[input];
Card b = _cards[cardSelectionIndex];
a = b;
请注意 a
的类型和 b
.这正确地给出了错误:“Cannot implicitly convert type '< filename.CardClass >' to System.Collections.Generic.List< filename.CardClass >'
”
您可能想要做的是向该列表中添加一张卡片
List<Card> a = _collections[input];
Card b = _cards[cardSelectionIndex];
a.Add(b);
或者只是
_collections[input].Add(_cards[cardSelectionIndex]);
关于c# - List< > Dictionary< K,List< >> 内部 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46145570/