コンストラクターで参照を渡したくない場合は、静的ディクショナリを使用して TestObject インスタンスを追跡し、TestObjectCollection にその静的ディクショナリから遅延読み込み方式でその親を検索させることができます。
例えば
public class TestObject
{
/// <summary>
/// Keep a list of all the instances of TestObject's that are created.
/// </summary>
internal static Dictionary<Guid, TestObject> _collections = new Dictionary<Guid, TestObject>();
/// <summary>
/// An ID to uniquely identify an instance of a TestObject
/// </summary>
public Guid ID { get; private set; }
/// <summary>
/// A reference to the collection which will be set in the constructor
/// </summary>
public TestObjectCollection TestObjects { get; private set; }
public TestObject()
{
//generate the unique id
this.ID = Guid.NewGuid();
this.TestObjects = new TestObjectCollection();
//add this testobject to the List of test objects.
_collections.Add(this.ID, this);
}
/// <summary>
/// Destructor, kill the TestObject from the list of TestObject's.
/// </summary>
~TestObject()
{
if (_collections.ContainsKey(this.ID))
{
_collections.Remove(this.ID);
}
}
}
public class TestObjectCollection : IEnumerable<TestObject>
{
private List<TestObject> _testObjects = new List<TestObject>();
public Guid ID { get; private set; }
public TestObject this[int i]
{
get
{
return _testObjects[i];
}
}
private TestObject _Parent = null;
public TestObject Parent
{
get
{
if (_Parent == null)
{
_Parent = TestObject._collections.Values.Where(p => p.TestObjects.ID == this.ID).FirstOrDefault();
}
return _Parent;
}
}
public TestObjectCollection()
{
this.ID = Guid.NewGuid();
}
public void Add(TestObject newObject)
{
if (newObject != null)
_testObjects.Add(newObject);
}
public IEnumerator<TestObject> GetEnumerator()
{
return _testObjects.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _testObjects.GetEnumerator();
}
}
テスト中...
class Program
{
static void Main(string[] args)
{
TestObject tObject = new TestObject();
Console.WriteLine("TestObject ID: " + tObject.ID);
Console.WriteLine("TestObject TestObjectCollection ID: " + tObject.TestObjects.ID);
Console.WriteLine("TestObject TestObjectCollection Parent ID: " + tObject.TestObjects.Parent.ID);
Console.WriteLine("Press any key...");
Console.ReadKey(true);
}
}
したがって、これが行うことは、それ自体に GUID ID を与える TestObject のコンストラクターにあります。次に、TestObjectCollection のインスタンスを作成します。
TestObjectCollection のコンストラクターでは、それ自体に GUID ID を与えます。
TestObject のコンストラクターに戻り、作成したばかりのコレクションに TestObjects を設定し、それ自体への参照を静的な TestObjects の Dictionary に追加します。TestObject の ID を上記の Dictionary のキーとして使用します。
次に、TestObjectCollection で、呼び出されるまでそれ自体を設定しないプロパティを使用してその静的辞書で検索することにより、親コレクションを取得します (TestObject コンストラクターがまだ参照を追加していないため、コンストラクターで決定できないため) )。
private TestObject _Parent = null;
public TestObject Parent
{
get
{
if (_Parent == null)
{
_Parent = TestObject._collections.Values.Where(p => p.TestObjects.ID == this.ID).FirstOrDefault();
}
return _Parent;
}
}