c#从chlid实例获取父对象
问题描述:
我尝试获取实例的父类型。
我该怎么办?
I try to get the parent Type of a instance. How can I do ?
示例:
public class a
{
public b { get; set; }
}
public class b
{
}
var a = new a();
a.b = new b();
var parentType = a.b.??GetParentInstanceType()??
答
您不能。
您需要手动向孩子添加属性以跟踪父母:
You'd need to add a property to the child manually to keep track of the parent:
这里是一种方法:
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();
当然,这里的问题是没有什么可以阻止您忘记设置 Parent
或设置了错误的 Parent
。
Of course the problem here is that nothing stops you from forgetting to set Parent
or setting the wrong Parent
.