我有这个功课,我只有1个问题,我不知道解决方案。我们有这个类,我们musn't创建另一个变量或方法...如何获取字典C#中的对象键的支持?
我有一个啤酒字典与<啤酒对象,诠释收入>。但是该方法只获得了Beer对象的名称(prop),而不是对象。
而且我没有其他想法,我怎么可以从字典
我只有2个想法得到了啤酒对象的名称,但这些不工作。
第一个是我尝试使用一个ContainsKey()方法。第二个是的foreach迭代
using System;
using System.Collections.Generic;
namespace PubBeer
{
public class Beer
{
string name;
int price;
double alcohol;
public string Name{ get { return name; } }
public int Price{ get; set; }
public double Alcohol{ get { return alcohol;} }
public Sör(string name, int price, double alcohol)
{
this.name= name;
this.price= price;
this.alcohol= alcohol;
}
public override bool Equals(object obj)
{
if (obj is Beer)
{
Beer other = (Beer)obj;
return this.name== other.name;
}
return false;
}
}
public class Pub
{
int income;
IDictionary<Beer, int> beers= new Dictionary<Beer, int>();
public int Income{ get; set; }
public int Sold(string beerName, int mug)
{
// Here the problem
beers; // Here I want to like this: beers.Contains(beerName)
// beers.ContainsKey(Object.Name==beerName) or someone like this
// foreach (var item in beers)
// {
// item.Key.Name== beerName;
// }
}
...
我可以建议改变你的关键。通过(可能)搜索字典中的每个关键字可以破坏字典的效率。 –
@my你确实是对的,但如果这是他的家庭作业,他的老师可能希望他学习一些东西(linq查询也许?) – fnurglewitz
我不认为linq ...因为他没有谈论linq-s唯一的接口在最后一课......但这是作业 – blaces