c#从chlid实例获取父对象 [英] c# get parent from chlid instance

查看:247
本文介绍了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.

这篇关于c#从chlid实例获取父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆