一种替代方法是使用基于字符串的索引器构建您自己的指定CarDictionary
索引器(假设Name
字段/属性为public
):
public class CarDictionary : List<Car>
{
public Car this[string name]
{
get { return this.Single(car => car.Name.Equals(name)); }
set {
var oldCar = this.SingleOrDefault(car => car.Name.Equals(name));
if (oldCar != null) base.Remove(oldCar);
value.Name = name;
base.Add(value);
}
}
public new void Add(Car car)
{
if (this.Any(c => c.Name.Equals(car.Name)))
throw new InvalidOperationException("Dictionary already contains a Car with the same name");
base.Add(car);
}
}
此外,您需要重新实现或隐藏其他基类方法,例如等AddRange
,Remove
以确保集合不会意外损坏。
如果您现在初始化您的汽车“字典”并添加Ford:
var cars = new CarDictionary();
var newCar = new Car("Ford", 4, 2387.4, 4535.7, 128.2);
cars["Ford"] = newCar;
字典状态是:
Number of cars: 1, name of first car: Ford
如果你然后尝试:
cars["Ford"].Name = "not Ford";
字典状态将是:
Number of cars: 1, name of first car: not Ford
接下来,使用重新实现的Add
方法添加一个新的Ford:
cars.Add(new Car("Ford", 6, 4000.0, 500.0, 100.0));
将产生以下字典状态:
Number of cars: 2, name of last car: Ford
尝试使用该方法添加另一个福特Add
将产生异常:
var anotherFord = new Car("Ford", 3, 1000.0, 50.0, 120.0);
cars.Add(anotherFord);
InvalidOperationException: Dictionary already contains a Car with the same name
但如果您改用索引器,新福特将取代旧的:
cars["Ford"] = anotherFord;
Number of cars: 2, name of last car: Ford
最后,使用索引器向Car
字典添加新的一个特点是索引器可能(应该?)更改添加的名称Car
:
cars["thought this was a Ford?"] = anotherFord;
Number of cars: 3, name of last car: thought this was a Ford?
据我所知,这将是索引器设置器的预期行为。如果不希望出现这种行为,只需删除该行
value.Name = name;
从索引器设置器实现。