1

我正在研究如何获取创建另一个对象的对象(或对象类型)。例如:

public class RootClass
{
    public class A
    {
        public void MethodFromA()
        {

        }
    }

    public class B
    {
        public A A_object = new A();
        public void MethodFromB() { }
    }

    B BObject = new B();
    A rootAObject = new A();

    public void DoMethod(A anA_object)
    {

    }

    main()
    {
        /* Somehow through reflection
         * get the instance of BObject 
         * of type B from only the info
         * given in anA_object or at
         * the very least just know that
         * anA_object was created in
         * class B and not root. */
        DoMethod(BObject.A_object);

        /* Same as above except know that
         * this A object came from root 
         * and is not from B class */
        DoMethod(rootAObject);
    }
}

附加信息:这只是一个快速代码,用于模拟我拥有的大型项目的一部分。问题是我有一个自定义类,它在许多其他类中实例化了很多地方。这个自定义类有一个函数,应该能够调用其中的任何函数或实例化它的类中的任何函数。非常通用的处理,但需要。基本上我需要“。”的倒数。所以对于objectA.objectB,我只需要通过将objectB传递给某个函数来找到objectA。

谢谢!

4

4 回答 4

1

No - this information isn't stored anywhere. Note that even if it were, it could easily become out of date, effectively. For example:

// Code as before
BObject.A_object = rootAObject;
rootAObject = null;
DoMethod(BObject.A_object);

What should that now show? The current value of BObject.A_object was created as rootAObject, but the current value of rootAObject is null. If you'd want that to show BObject as the "owner" then you're not really talking about creation at all... and at that point, you need to deal with the possibility that an object has multiple references to it.

Please give us more information about the bigger picture: what problem are you really trying to solve?

于 2010-08-16T05:29:46.053 回答
0

I believe what you're looking for is the property DeclaringType, defined on the System.Type instance that you're interested in. See DeclaringType documentation.

于 2010-08-16T05:19:22.017 回答
0

DeclaringType will only tell you the enclosing type of the code model, but what you are after is identifying object creation point.

There is no easy way to do it other than reading the individual MethodBody IL. IL code for creating an object is newobj. To implement this, you will need to read the MethodBody for every method in your assembly and identify the method that contains newobj instruction with type operand of the object type you are after.

于 2010-08-16T05:34:39.223 回答
0

Solved by making all my objects derive from a custom object with a parent parameter.

于 2011-04-15T04:20:58.327 回答