问题
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