如何解决循环引用? [英] How to solve circular reference?

查看:310
本文介绍了如何解决循环引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我的一个朋友曾问我的问题,你怎么解决循环引用的问题,像A类具有B类具有属性之一,而B类有一个类的属性之一。

Recently one of my friend has asked me question, how do you solve the circular reference problems like Class A has class B has one of the property, while Class B has Class A has one of the property.

如何为这些类型的问题做建筑师?

How to do architect for those kind of problems?

如果你把NHibernate的的一个例子,将有对象间的父柴尔德关系

If you take an example of NHibernate, there will be parent -child relationship between objects.

它是如何能够处理那些父子的情景?

How is it able to handle those parent child scenarios?

推荐答案

在的时候我已经有两件事相互引用大多数情况下,我创建了一个接口,除去循环引用。例如:

In most cases when I've had to have two things reference each other, I've created an interface to remove the circular reference. For example:

public class Foo
{
    Bar myBar;
}

public class Bar
{
    Foo myFoo;
}

依赖关系图:

Foo     Bar
 ^       ^
 |       |
Bar     Foo

foo依赖于酒吧,酒吧,但也要看符。如果他们是在单独的组件,你将有问题的建筑,特别是如果你做一个干净的重建。

Foo depends on Bar, but Bar also depends on Foo. If they are in separate assemblies, you will have problems building, particularly if you do a clean rebuild.

public interface IBar
{
}

public class Foo
{
    IBar myBar;
}

public class Bar : IBar
{
    Foo myFoo;
}

依赖关系图:

Foo, IBar     IBar
    ^          ^
    |          |
   Bar        Foo

Foo和Bar都取决于伊巴尔。没有循环依赖,如果被伊巴尔放置在自己组装,Foo和Bar在单独的组件是将不再是一个问题。

Both Foo and Bar depend on IBar. There is no circular dependency, and if IBar is placed in its own assembly, Foo and Bar being in separate assemblies will no longer be an issue.

这篇关于如何解决循环引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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