// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.Collections.ObjectModel;
namespace Microsoft.Xna.Framework.Content.Pipeline
{
///
/// Provides a collection of child objects for a content item.
///
/// Links from a child object to its parent are maintained as the collection contents are modified.
///
///
///
public abstract class ChildCollection : Collection
where TParent : class
where TChild : class
{
TParent parent;
///
/// Creates an instance of ChildCollection.
///
/// Parent object of the child objects returned in the collection.
protected ChildCollection(TParent parent)
: base()
{
if (parent == null)
throw new ArgumentNullException("parent");
this.parent = parent;
}
///
/// Removes all children from the collection.
///
protected override void ClearItems()
{
// Remove parent reference from each child before clearing
foreach (TChild child in this)
SetParent(child, default(TParent));
base.ClearItems();
}
///
/// Gets the parent of a child object.
///
/// The child of the parent being retrieved.
/// The parent of the child object.
protected abstract TParent GetParent(TChild child);
///
/// Inserts a child object into the collection at the specified location.
///
/// The position in the collection.
/// The child object being inserted.
protected override void InsertItem(int index, TChild item)
{
// Make sure we have a
if (item == null)
throw new ArgumentNullException("child");
if (GetParent(item) != null)
throw new InvalidOperationException("Child already has a parent");
SetParent(item, parent);
base.InsertItem(index, item);
}
///
/// Removes a child object from the collection.
///
/// The index of the item being removed.
protected override void RemoveItem(int index)
{
TChild child = this[index];
SetParent(child, default(TParent));
base.RemoveItem(index);
}
///
/// Modifies the value of the child object at the specified location.
///
/// The index of the child object being modified.
/// The new value for the child object.
protected override void SetItem(int index, TChild item)
{
if (item == null)
throw new ArgumentNullException("child");
if (GetParent(item) != null)
throw new InvalidOperationException("Child already has a parent");
TChild child = this[index];
SetParent(child, default(TParent));
SetParent(item, parent);
base.SetItem(index, item);
}
///
/// Modifies the value of the parent object of the specified child object.
///
/// The child of the parent being modified.
/// The new value for the parent object.
protected abstract void SetParent(TChild child, TParent parent);
}
}