简体   繁体   English

From元素如何访问列表

[英]From element how to access List

I have one element from list, how to access this list count from element, like this: 我有一个来自列表的元素,如何从元素访问此列表计数,如下所示:

    public void Setup()
    {
    var myList = new List<T>();
    myList.add(new T(1));
    myList.add(new T(2));
    myList.add(new T(3));
    myList.add(new T(4));


    var myElement = myList.Last();

    MyFunctionReflection(myElement);
    }



    public void MyFunctionReflection(T element)
    {
    var countElements = ????? //How determine elements in Ilist from element using reflection
   Console.Write("the list that owns the element, contains {0} elements.",countElements);
    }

For all practical purposes, this is not possible. 出于所有实际目的,这是不可能的。

Theoretically, using unsafe code, it might be possible to walk through the entire program's memory space, look for every single List object, see if it contains a reference to the object in question, and then access it's count. 从理论上讲,使用unsafe代码,可能可以遍历整个程序的内存空间,查找每个List对象,查看它是否包含对所讨论对象的引用,然后访问其计数。 While this might be theoretically possible though, it's almost certainly not an acceptable solution to virtually any problem, and would be prohibitively difficult/time consuming to try to code. 尽管从理论上讲这可能是可行的,但几乎可以肯定,这对于几乎任何问题都不是可接受的解决方案,并且尝试进行编码将非常困难/耗时。

You can't. 你不能

You will have to either pass-in the count, or pass-in a reference to the list: 您将必须传递计数,或传递对列表的引用:

public void MyFunctionReflection(T element, int count) ...

or 要么

public void MyFunctionReflection(T element, IList<T> list) ...

There is no direct link between an element and the List to which it belongs. 元素与其所属的列表之间没有直接链接。

What you could do, is when you instantiate your element, pass it a reference to the List and make it available through a property on the element. 您可以做的是在实例化元素时,将其传递给List的引用,并通过元素上的属性使其可用。

You Element class: 您元素类:

public class Element
{
    public List<Element> ParentList;

    public Element(int value, List<Element> parent)
    {
        ...
        ParentList = parent;
    }
}

Then in your main code: 然后在您的主要代码中:

var myList = new List<T>();
myList.add(new T(1, myList));
myList.add(new T(2, myList));
myList.add(new T(3, myList));

then later: 然后再:

var countElements = myElement.ParentList.Count; // ParentList is the reference to the List<T> that was passed to the constructor.

Cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM