如何获得一个集合的父对象?

本文关键字:集合 对象 一个 何获得 | 更新日期: 2023-09-27 18:07:53

在c#中,如果我有一个具有集合的对象,是否可以检索包含该集合的对象?

下面是一个例子:

public class TestObject
{
    public string name { get; set; }
    public TestObjectCollection testObjects{ get; set; } 
}

TestObjectCollection集合继承自CollectionBase,是TestObjects的集合。

下面是一个示例实现:

  • 创建TestObject,名称为"Test1"
  • 名称为"Test1"TestObject有一个TestObjectCollectionTestObject的名称为"Test2"

如果我有名称为"Test2"TestObject,我怎么能得到名称为"Test1"TestObject

谢谢

如何获得一个集合的父对象?

做到这一点的唯一方法是在子对象中保留对父对象的引用。您可以在创建子对象时执行此操作:

this.testObjects = new TestObjectCollection(this);
在TestObjectCollection的构造函数中:
public TestObject ParentObject { get; set; }
public TestObjectCollection(TestObject parent)
{
    ParentObject = parent;
    ...
}

也许你可以这样做:

using System;
using System.Collections.Generic;
public class TestObject
{
    private TestObjectCollection _testObjects;
    public string name { get; set; }
    public TestObjectCollection parentCollection { get; set; }
    public TestObjectCollection testObjects 
    { 
        get
        {
            return _testObjects;
        }
        set 
        {
            _testObjects = value;
            _testObjects.parent = this;
        }
    }
}
public class TestObjectCollection
{
    private List<TestObject> _testObjects;
    public TestObject parent { get; set; }
    public TestObjectCollection()
    {
        _testObjects = new List<TestObject>();
    }
    public void Add(TestObject testObject)
    {
        testObject.parentCollection = this;
        _testObjects.Add(testObject);
    }
    public TestObject this[int i] {
        get {
            return _testObjects[i];
        }
    }
}

public class Test
{
    public static void Main()
    {
        // your code goes here
        TestObject test1 = new TestObject();
        TestObject test2 = new TestObject();
        var collection = new TestObjectCollection();
        collection.Add(test2);
        test1.testObjects = collection;
        if (test2.parentCollection.parent == test1)
        {
            Console.WriteLine("Done");
        }
        else
        {
            Console.WriteLine("Fail");
        }
    }
}

以List为例

除非您显式地对父子关系进行编码(如Yogesh的回答),否则无法找到"父"——很大程度上是因为可以有多个这样的父:

public class TestObject
{
    public string name { get; set; }
    public TestObjectCollection testObjects{ get; set; } 
}
public class TestObjectCollection : CollectionBase
{
    public void Add(TestObject to)
    {
        this.List.Add(to);
    }
}
void Main()
{
    TestObjectCollection children = new TestObjectCollection();
    TestObject child = new TestObject { name = "child" };
    children.Add(child);
    TestObject parent = new TestObject { name = "parent", testObjects = children }; 
    TestObject otherParent = new TestObject { name = "otherParent", testObjects = children };   
    TestObject stepParent = new TestObject { name = "stepParent", testObjects = children }; 
    TestObject inLocoParentis = new TestObject { name = "inLocoParentis", testObjects = children };
    // and we can keep going on and on and on ...   
}

如果你不想在构造函数中传递引用,你可以使用静态字典来跟踪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的构造函数中,它将TestObject的集合设置为它刚刚创建的集合,然后将对自身的引用添加到TestObjects的Dictionary中,该Dictionary是静态的。它使用TestObject的ID作为所述字典的Key。

然后在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;
        }
    }