c# get parent from chlid instance

∥☆過路亽.° 提交于 2020-01-25 03:35:06

问题


I try to get the parent Type of a instance. How can I do ?

Example :

public class a
{
     public b { get; set; }
}

public class b
{

}


var a = new a();
a.b = new b();

var parentType = a.b.??GetParentInstanceType()??

回答1:


You can't.

You'd need to add a property to the child manually to keep track of the parent:

Here is one way:

public class A
{
    public B<A> Child { get; set; }
}

public class B<T>
{
    public T Parent { get; set; }
}

A a = new A();
a.Child = new B<A>();
a.Child.Parent = a;

Type parentType = a.Child.Parent.GetType();

Of course the problem here is that nothing stops you from forgetting to set Parent or setting the wrong Parent.



来源:https://stackoverflow.com/questions/13072077/c-sharp-get-parent-from-chlid-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!