How to solve circular reference?

前端 未结 6 623
悲&欢浪女
悲&欢浪女 2020-11-28 07:28

How do you solve circular reference problems like Class A has class B as one of its properties, while Class B has Class A as one of its properties?

How to do archite

6条回答
  •  甜味超标
    2020-11-28 07:41

    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:

    BEFORE

    public class Foo
    {
        Bar myBar;
    }
    
    public class Bar
    {
        Foo myFoo;
    }
    

    Dependency graph:

    Foo     Bar
     ^       ^
     |       |
    Bar     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.

    AFTER

    public interface IBar
    {
    }
    
    public class Foo
    {
        IBar myBar;
    }
    
    public class Bar : IBar
    {
        Foo myFoo;
    }
    

    Dependency graph:

    Foo, IBar     IBar
        ^          ^
        |          |
       Bar        Foo
    

    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.

提交回复
热议问题