.net 有没有办法在CLR中创建一个WeakList或者WeakCollection(比如WeakReference)?

wljmcqd8  于 2023-01-06  发布在  .NET
关注(0)|答案(4)|浏览(140)

使用List<WeakReference>不会像我想要的那样工作。我想要的是当WeakReferences引用的对象被垃圾收集时,WeakReferences会自动从列表中删除。
ConditionalWeakTable<TKey,TValue>也不能让我满意,因为尽管它的键和值是弱引用和可收集的,但你不能枚举它们!

4xrmg8kj

4xrmg8kj1#

我同意实现WeakList<T>是可能的,但我不认为它是完全“容易”的。欢迎使用我的实现hereWeakCollection<T>类依赖于WeakReference<T>,而WeakReference<T>又依赖于SafeGCHandle

yqlxgs2m

yqlxgs2m2#

您可以很容易地实现一个WeakList<T>类,它将 Package 一个List<WeakReference>
当对象被垃圾收集时,没有办法自动移除它们,因为不可能检测到这种情况发生的时间。(垃圾收集的)对象,方法是检查WeakReference.IsAlive属性。然而,我不推荐这种方法,因为从客户端的Angular 来看,它可能导致令人困惑的行为。我建议实现一个Purge方法来删除死条目,您可以显式调用该方法。
下面是一个示例实现:

public class WeakList<T> : IList<T>
{
    private List<WeakReference<T>> _innerList = new List<WeakReference<T>>();

    #region IList<T> Members

    public int IndexOf(T item)
    {
        return _innerList.Select(wr => wr.Target).IndexOf(item);
    }

    public void Insert(int index, T item)
    {
        _innerList.Insert(index, new WeakReference<T>(item));
    }

    public void RemoveAt(int index)
    {
        _innerList.RemoveAt(index);
    }

    public T this[int index]
    {
        get
        {
            return _innerList[index].Target;
        }
        set
        {
            _innerList[index] = new WeakReference<T>(value);
        }
    }

    #endregion

    #region ICollection<T> Members

    public void Add(T item)
    {
        _innerList.Add(new WeakReference<T>(item));
    }

    public void Clear()
    {
        _innerList.Clear();
    }

    public bool Contains(T item)
    {
        return _innerList.Any(wr => object.Equals(wr.Target, item));
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        _innerList.Select(wr => wr.Target).CopyTo(array, arrayIndex);
    }

    public int Count
    {
        get { return _innerList.Count; }
    }

    public bool IsReadOnly
    {
        get { return false; }
    }

    public bool Remove(T item)
    {
        int index = IndexOf(item);
        if (index > -1)
        {
            RemoveAt(index);
            return true;
        }
        return false;
    }

    #endregion

    #region IEnumerable<T> Members

    public IEnumerator<T> GetEnumerator()
    {
        return _innerList.Select(x => x.Target).GetEnumerator();
    }

    #endregion

    #region IEnumerable Members

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }

    #endregion

    public void Purge()
    {
        _innerList.RemoveAll(wr => !wr.IsAlive);
    }
}

此类使用以下类和扩展方法:

WeakReference<T>(只是WeakReference周围的强类型 Package 器)

[Serializable]
public class WeakReference<T> : WeakReference
{
    public WeakReference(T target)
        : base(target)
    {
    }

    public WeakReference(T target, bool trackResurrection)
        : base(target, trackResurrection)
    {
    }

    public WeakReference(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
    }

    public new T Target
    {
        get
        {
            return (T)base.Target;
        }
    }
}

IndexOf(与IList<T>.IndexOf相同,但适用于IEnumerable<T>

public static int IndexOf<T>(this IEnumerable<T> source, T item)
    {
        var entry = source.Select((x, i) => new { Value = x, Index = i })
                    .Where(x => object.Equals(x.Value, item))
                    .FirstOrDefault();
        return entry != null ? entry.Index : -1;
    }

CopyTo(与IList<T>.CopyTo相同,但适用于IEnumerable<T>

public static void CopyTo<T>(this IEnumerable<T> source, T[] array, int startIndex)
    {
        int lowerBound = array.GetLowerBound(0);
        int upperBound = array.GetUpperBound(0);
        if (startIndex < lowerBound)
            throw new ArgumentOutOfRangeException("startIndex", "The start index must be greater than or equal to the array lower bound");
        if (startIndex > upperBound)
            throw new ArgumentOutOfRangeException("startIndex", "The start index must be less than or equal to the array upper bound");

        int i = 0;
        foreach (var item in source)
        {
            if (startIndex + i > upperBound)
                throw new ArgumentException("The array capacity is insufficient to copy all items from the source sequence");
            array[startIndex + i] = item;
            i++;
        }
    }
ldfqzlk8

ldfqzlk83#

对于任何需要在.NET 2.0或3.5中使用ConditionalWeakTable的人,这里有一个它的后端:https://github.com/theraot/Theraot/wiki/Features

lsmepo6l

lsmepo6l4#

使用java.util.WeakHashMap并将对象存储在键中怎么样?值可以是任何伪对象。但是,由于Map没有排序,因此只能获得WeakSet功能。

相关问题