[英]How can I determine if an object is reachable within an object graph in C#?
I have a pretty complex object graph G
with an object o1
in G
. 我有一个相当复杂的对象图
G
与对象o1
在G
。 G
is to be written into a database using NHibernate. 使用NHibernate将
G
写入数据库。 However, if there already is a persistent entry of o1
(let's call it o1_p
) in the database, I substitute o1
for o1_p
. 但是,如果数据库中已经存在
o1
的持久项(我们称其为o1_p
),则用o1
代替o1_p
。 Hence there should be no redundant entries in the database. 因此,数据库中不应有多余的条目。 Now I let NHibernate do its job and afterwards I look into the database.
现在,我让NHibernate完成工作,然后再查看数据库。 Now I have exactly the situation I tried to avoid.
现在,我完全可以避免这种情况。 There are entries for the original
o1_p
object plus o1
in the database. 数据库中有原始
o1_p
对象加o1
条目。 The only explanation I have so far is that o1
is reachable via another route in G
so hibernate puts it into the database. 到目前为止,我唯一的解释是
o1
可以通过G
另一条路由到达,因此休眠将其放入数据库中。 Is there a way I can determine if this is the case, ie can I ask the garbage collector how many references there are to o1
. 有没有一种方法可以确定是否是这种情况,即可以问垃圾回收器对
o1
引用数是多少? Or to speak in graph language: How many incoming edges does o1
have? 或用图形语言说话:
o1
有多少个入局边?
No, you can't ask the garbage collector how many references there are to o1: .NET doesn't use reference counting. 不,您不能问垃圾回收器对o1有多少引用:.NET不使用引用计数。
Basically you'd have to do all the graph navigation yourself, which will probably mean making your object graph implement some sort of visitor algorithm, combined with a cache of objects you've already examined. 基本上,您必须自己进行所有图导航,这可能意味着使您的对象图实现某种访问者算法,并结合已经检查过的对象的缓存。 And yes, this is similar to what the GC would do, but I don't believe there's any way of hooking into its processing.
是的,这是类似于在GC会做,但我不相信有挂接到其处理任何方式。 (And there are probably edge cases involving special tricks where the GC knows something isn't garbage and ignores it anyway, which wouldn't be suitable for your code.)
(并且可能存在一些涉及特殊技巧的极端情况,其中GC知道某些东西不是垃圾,无论如何都会忽略它,这不适合您的代码。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.