Emm*_*lin 0 c# arrays collections dictionary generic-collections
我正试图在这里打印出一个数组/集合.我有一个包含以下代码的类文件来打印文本:
//Display All
public void Display()
{
Console.WriteLine(ID + "\t" + Product + "\t" + Category + "\t" + Price + "\t" + Stock + "\t" + InBasket);
}
Run Code Online (Sandbox Code Playgroud)
然后,在main中我尝试使用以下方法将其实际打印到屏幕上:
foreach (KeyValuePair<int, Farm_Shop> temp in products)
{
//display each product to console by using Display method in Farm Shop class
temp.Display();
}
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
'System.Collections.Generic.KeyValuePair<int,Farm_Shop_Assignment.Farm_Shop>'
does not contain a definition for 'Display' and no extension method 'Display'
accepting a first argument of type
'System.Collections.Generic.KeyValuePair<int,Farm_Shop_Assignment.Farm_Shop>'
could be found (are you missing a using directive or an assembly reference?)
Run Code Online (Sandbox Code Playgroud)
这是我要打印的实际内容:
products = new Dictionary<int, Farm_Shop>
{
{ 1, new Farm_Shop(1, "Apple", "Fruit\t", 0.49, 40, 'n') },
{ 2, new Farm_Shop(2, "Orange", "Fruit\t", 0.59, 35, 'n') }
};
Run Code Online (Sandbox Code Playgroud)
根据我的理解,这不起作用,因为我只发送要打印的数组/集合,而不是如果你知道我的意思,那就是要在它之前出现的int.
有人能告诉我如何让它正确打印.
非常感激.谢谢.
Display()是一种方法Farm_Shop.您不能直接在类型的对象上调用它KeyValuePair<int, Farm_Shop>.您应该这样做以访问键/值对中的Farm_Shop实例:
foreach (KeyValuePair<int, Farm_Shop> temp in products)
{
//display each product to console by using Display method in Farm Shop class
temp.Value.Display();
}
Run Code Online (Sandbox Code Playgroud)
或者遍历Values属性,因为密钥不会为您增加太多(因为它来自一个属性Farm_Shop:
foreach (Farm_Shop temp in products.Values)
{
//display each product to console by using Display method in Farm Shop class
temp.Display();
}
Run Code Online (Sandbox Code Playgroud)