如何获取在同一对象类型中声明的对象的第n个引用?

时间:2016-10-01 13:52:45

标签: c#

我遇到一个问题,一个对象里面有相同的对象,这个对象在另一个对象里面,依此类推,对于exameple:

class SomeObject
{
    SomeObject obj;
}

var obj= new SomeObject{ };
obj.obj= new SomeObject{ };
obj.obj.obj= new SomeObject{ };

我的问题是如何找到最新的对象,我可以使用它:

if(obj.obj== null)
{
    obj.obj= new SomeObject{ }; //assign it a new object
}

但如何自动执行此操作?如果相应的对象没有实现IEnumerable接口,如何遍历所有对象?以及如何获取未初始化的最新对象的引用,以便我可以为其分配一个新对象而不必执行此操作:

obj.obj.obj.obj = new SomeObject{ };

4 个答案:

答案 0 :(得分:2)

存在递归的概念:MSDN您可以声明一个方法并进行递归调用,直到找到您想要的内容。

static void AddObject(SomeObject currentObject, SomeObject child) {
  if(currentObject == null) return; 
  else if(currentObject.obj != null) AddObject(currentObject.obj, child);
  else currentObject.obj = child;
}

答案 1 :(得分:1)

你可以反过来,从而消除长obj.obj.obj

// Create the last object first and then prepend others.
SomeObject root = null;
root = new SomeObject { obj = root };
root = new SomeObject { obj = root };
root = new SomeObject { obj = root };
root = new SomeObject { obj = root };

或者,如果您不想反转对象的顺序,请同时保留对最后一个对象的引用

SomeObject head = null; // References first object
SomeObject tail = null; // References last object.

// Add object
var item = new SomeObject();
if (tail == null) { // head is null as well.
    head = item;
    tail = item;
} else {
    tail.obj = item;
    tail = item;
}

结果实际上是一个链表。通过一些调整,你得到:

public class Node<T>
{
    public T Data { get; set; }
    public Node<T> Next { get; set; }
}

public class LinkedList<T>
{
    public Node<T> Head { get; set; }
    public Node<T> Tail { get; set; }

    public void Add(T data)
    {
        var node = new Node<T>{ Data = data };
        if (Tail == null) { // Head is null as well.
            Head = node;
            Tail = node;
        } else {
            Tail.Next = node;
            Tail = node;
        }
    }
}

答案 2 :(得分:0)

您可以使用&#34; while&#34;循环进入对象:

var obj = new SomeObject{ };
obj.obj = new SomeObject{ };
obj.obj.obj = new SomeObject{ };
var loopObj = obj;
while (loopObj.obj != null){
   loopObj = loopObj.obj;
}

loopObj是最后一个对象。

答案 3 :(得分:0)

可能是下一个方向:

var obj= new SomeObject{ };
            obj.obj= new SomeObject{ };
            obj.obj.obj= new SomeObject{ };

            var lastObject = obj;
            int i = 0;
            while (lastObject.obj != null)
            {
                i++;
                lastObject = lastObject.obj;
            }
            Console.WriteLine ("i={0}; lastObject={1}", i, lastObject);