// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Windows.Controls.DataVisualization
{
///
/// A bag of weak references to items.
///
/// The type of the item.
internal class WeakReferenceBag : IEnumerable
where T : class
{
///
/// Gets or sets the list of event listeners.
///
private IList Items { get; set; }
///
/// Initializes a new instance of the WeakEvent class.
///
public WeakReferenceBag()
{
this.Items = new List();
}
///
/// Adds an item to the bag.
///
/// The item to add to the bag.
public void Add(T item)
{
Debug.Assert(item != null, "listener must not be null.");
this.Items.Add(new WeakReference(item));
}
///
/// Removes an item from the bag.
///
/// The item to remove.
public void Remove(T item)
{
Debug.Assert(item != null, "listener must not be null.");
int count = 0;
while (count < this.Items.Count)
{
object target = this.Items[count].Target;
if (!this.Items[count].IsAlive || object.ReferenceEquals(target, item))
{
this.Items.RemoveAt(count);
}
else
{
count++;
}
}
}
///
/// Returns a sequence of the elements in the bag.
///
/// A sequence of the elements in the bag.
public IEnumerator GetEnumerator()
{
int count = 0;
while (count < this.Items.Count)
{
object target = this.Items[count].Target;
if (!this.Items[count].IsAlive)
{
this.Items.RemoveAt(count);
}
else
{
yield return (T)target;
count++;
}
}
}
///
/// Returns a sequence of the elements in the bag.
///
/// A sequence of the elements in the bag.
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((IEnumerable) this).GetEnumerator();
}
}
}