如果您不想在构造函数中传递引用,则可以使用静态字典来跟踪 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);
}
}
所以它的作用是在 TestObject 的构造函数中给自己一个 GUID ID。然后它创建一个TestObjectCollection 的实例。
在 TestObjectCollection 的构造函数中,它给自己一个 GUID ID。
回到 TestObject 的构造函数中,它将 TestObjects 设置到它刚刚创建的集合中,然后将对自身的引用添加到静态的 TestObjects 字典中。它使用 TestObject 的 ID 作为所述字典的键。
然后在 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;
}
}