如何确定 C# 中对象图中的对象是否可访问?
我有一个非常复杂的对象图 G
,其中 G
中有一个对象 o1
。 G
将使用 NHibernate 写入数据库。 但是,如果数据库中已经存在 o1
的持久条目(我们称之为 o1_p
),我会将 o1
替换为 o1_p
。 因此数据库中不应有多余的条目。 现在我让 NHibernate 完成它的工作,然后我查看数据库。 现在我遇到了我试图避免的情况。 数据库中有原始 o1_p
对象和 o1
的条目。 到目前为止,我唯一的解释是 o1
可以通过 G
中的另一条路由到达,因此 hibernate 将其放入数据库中。 有没有办法可以确定是否是这种情况,即我可以询问垃圾收集器有多少个对 o1
的引用。 或者用图语言来说:o1
有多少条传入边?
I have a pretty complex object graph G
with an object o1
in G
. G
is to be written into a database using NHibernate. 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
. Hence there should be no redundant entries in the database. Now I let NHibernate do its job and afterwards I look into the database. Now I have exactly the situation I tried to avoid. There are entries for the original o1_p
object plus o1
in the database. The only explanation I have so far is that o1
is reachable via another route in G
so hibernate puts it into the database. Is there a way I can determine if this is the case, i.e. can I ask the garbage collector how many references there are to o1
. Or to speak in graph language: How many incoming edges does o1
have?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,您不能询问垃圾收集器有多少个对 o1 的引用:.NET 不使用引用计数。
基本上,您必须自己完成所有图形导航,这可能意味着使您的对象图实现某种访问者算法,并结合您已经检查过的对象的缓存。 是的,这与 GC 所做的类似,但我不相信有任何方法可以挂钩它的处理。 (并且可能存在涉及特殊技巧的边缘情况,其中 GC 知道某些东西不是垃圾并忽略它,这不适合您的代码。)
No, you can't ask the garbage collector how many references there are to o1: .NET doesn't use reference counting.
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. (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.)