字典上的安全迭代

时间:2014-08-15 08:35:44

标签: c# dictionary

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语句。我怎么能这样做?

0 个答案:

没有答案