C#-如何使用该键的值获取对字典键对象的引用
我正在建造一个提供一些服务的车库。 有关问题的类别如下:C#-如何使用该键的值获取对字典键对象的引用,c#,dictionary,equals,gethashcode,C#,Dictionary,Equals,Gethashcode,我正在建造一个提供一些服务的车库。 有关问题的类别如下: 班级车库 抽象类车辆 从车辆(汽车、摩托车、卡车)衍生的3类 在车库的课堂上,我有一本字典,它把所有的车辆都当作钥匙,把它们在车库里的地位当作价值 为了实践不同的C#功能,我覆盖了车辆GetHashCode()和Equals(),我想用它来获得一个对O(1)中车牌号相同的车辆的引用 我所做的是从字典中克隆一个随机载体,将其车牌号更改为所需的车牌号,然后检查是否包含该载体,返回布尔值 下面的代码让我知道了那辆车的价值(车库中的车辆状态),我
class Garage
{
public enum eServiceStatus
{
Done,
Paid,
Active
}
private static Dictionary<Vehicle, eServiceStatus> m_Vehicles = new Dictionary<Vehicle, eServiceStatus>();
private static Vehicle findVehicleByLicensePlate(string i_LicensePlate)
{
Vehicle vehicleToFind = Vehicles.ElementAtOrDefault(0).Key.Clone();
if (vehicleToFind == default(Vehicle))
{
throw new ArgumentException();
}
vehicleToFind.LicensePlate = i_LicensePlate;
if (Vehicles.ContainsKey(vehicleToFind))
{
vehicleToFind = Vehicles[vehicleToFind];
}
return vehicleToFind;
}
/* ... */
}
您可以使用类似于
Vehicles.Keys.FirstOrDefault(v=>v.LicensePlate==i\u LicensePlate)
的东西,它将返回车辆或null。另外,Vehicles.ElementAtOrDefault(0.Key.Clone()
是一个相当糟糕的选择,因为如果您的字典为空,ElementAtOrDefault(0)
将返回null,并且以下密钥访问将引发异常。@JackT.Spades yea我刚刚得到了该异常。我不确定我是否可以使用lambda表达式,这是一个学校项目,我们还没有在课堂上了解到这一点,有没有其他在C#2.0中支持的方法?LINQ只是方便每一件东西。因此,如果不是一个选项,你可以用手在字典上循环并检查每一对<代码>车辆v=空;foreach(车辆中的var对)if(pair.Key.LicensePlate==i_LicensePlate){v=pair.Key;break;}。在我看来,您的许多代码可以通过保留另一个字典,字典
,将车牌映射到车辆来简化。不可能在O(1)时间内完成吗?没有循环通过它?即使所有的散列都准备好了?
abstract class Vehicle
{
private string m_LicensePlate;
public Vehicle(string i_LicensePlate)
{
m_LicensePlate = i_LicensePlate;
}
public string LicensePlate
{
get { return m_LicensePlate; }
set { m_LicensePlate = value; }
}
public override bool Equals(object obj)
{
bool equals = false;
Vehicle vehicleToCheck = obj as Vehicle;
if (vehicleToCheck != null)
{
equals = vehicleToCheck.LicensePlate == this.LicensePlate;
}
return equals;
}
public override int GetHashCode()
{
return this.LicensePlate.GetHashCode();
}
}