public abstract class FieldObjects<T> : ConcurrentDictionary<int, T> where T : FieldObject
{
public Field Field { get; private set; }
public FieldObjects(Field field)
: base()
{
this.Field = field;
}
public virtual void Add(T value)
{
value.Field = this.Field;
value.ObjectId = this.Field.AssignObjectId();
this.AddOrUpdate(value.ObjectId, value, null);
}
public virtual void Remove(T value)
{
value.Field = null;
value.ObjectId = -1;
this.TryRemove(value.ObjectId, out value);
}
public IEnumerable<T> GetInRange(FieldObject reference, int range)
{
foreach (T fieldObject in this.Values)
{
if (reference.Position.DistanceFrom(fieldObject.Position) <= range)
{
yield return fieldObject;
}
}
}
}
我有这个抽象类。我希望能够以安全的方式迭代它的值(不是KeyValuePair,但仅限值),所以我不必每次都使用lock
语句。我怎么能这样做?