【问题标题】:c# get parent from chlid instancec# 从子实例中获取父级
【发布时间】:2012-10-15 20:13:21
【问题描述】:

我尝试获取实例的父类型。 我该怎么办?

例子:

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

public class b
{

}


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

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

【问题讨论】:

  • 你想从 b 获取 a 的类型?
  • 请更清楚你的名字。可能会为ab 找到更好的名称,并解释您所说的parentchild 的含义。
  • 我认为这是不可能的,因为b 的实例不包含有关引用它的a 实例的任何信息
  • 如果你使用a.b,那么a.GetType()不会做你想做的事吗?
  • @JonB 我对同样的事情感到困惑......也许这个问题还有一些更深层次的问题...... O_o

标签: c# class reflection types instance


【解决方案1】:

你不能。

您需要手动向子级添加一个属性以跟踪父级:

这是一种方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多