0

当前程序导致stackoverflow异常,我知道为什么。我怎样才能避免这里的循环依赖。我怎样才能让这三个类彼此独立,尽管这些类是相互依赖的(假设这些类中的方法互相引用)。如何在这种情况下避免循环依赖?

namespace CircularDependency_1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      A a = new A(); 
      B b = new B(); 
      Console.WriteLine("executed"); 
      Console.ReadLine(); 
     } 
    } 

    public class B 
    { 
     public A a; 

     public B() 
     { 
      a = new A(); 
      Console.WriteLine("Creating B"); 
     } 
    } 

    public class A 
    { 
     public B b; 

     public A() 
     {  
      b = new B(); 
      Console.WriteLine("Creating A"); 
     } 
    } 

    public class C 
    { 
     public A a; 
     public B b; 

     public C() 
     { 
      a = new A(); 
      b = new B(); 
      Console.WriteLine("Creating C"); 
     } 
    } 

} 
+1

为什么'新'''A'和' B'在另一个的构造函数?它背后的理由是什么?它期望做什么?你只需要1个A和1B实例,它们是相互引用的?如果没有这些信息,你的问题就像:我有一个类class A {A(){new A(); }}'我应该如何解决它?没有意义的答案 –

回答

0

这不是依赖注入,而是在构造函数中创建它。 你应该保持A和B构造空,做这样的事情在C:

public class C 
    { 
     public A a; 
     public B b; 

     public C() 
     { 
      a = new A(); 
      b = new B(); 
      a.setB(b); 
      b.setA(a); 
     } 
    } 

在另一方面,你应该检查,如果你真的需要有这种双重参考。

编辑: 我看你是不是真的使用类C.如果你想这样做主,就是同一件事:

static void Main(string[] args) 
    { 
     A a = new A(); 
     B b = new B(); 
     a.setB(b); 
     b.setA(a); 
    } 
+0

仍然会出现stackoverflow例外 –

+0

mmm,不,为什么? – leoxs

1

你不应该new'ing你的对象。相反,您需要将它们作为参数传递给构造函数。您需要重构你的代码:

public class A { 
    B _b; 
    public A(B b) { 
    _b = b; 
    Console.WriteLine("Creating A"); 
    } 
} 
public class B { 
    A _a; 
    public B(A a) { 
    _a = a; 
    Console.WriteLine("Creating B"); 
    } 
} 
public class C { 
    A _a; 
    B _b; 
    public C (A a, B b) { 
    _a = a; 
    _b = b; 
    Console.WriteLine("Creating C"); 
    } 
} 

然后,你需要重构功能出A(或B)到另一个类d:

public class A { 
    D _d; 
    public A(D d) { 
    _d = d; 
    Console.WriteLine("Creating A"); 
    } 
} 
public class B { 
    A _a; 
    D _d; 
    public B(A a, D d) { 
    _a = a; 
    _d = d; 
    Console.WriteLine("Creating B"); 
    } 
} 

public class C { 
    A _a; 
    B _b; 
    public C (A a, B b) { 
    _a = a; 
    _b = b; 
    Console.WriteLine("Creating C"); 
    } 
} 

public class D { 
    public D() { 
    Console.WriteLine("Creating D"); 
    } 
} 

然后,您可以创建对象作为

D d = new D(); 
A a = new A(d); 
B b = new B(a, d); 
C c = new C(a, b); 
Console.WriteLine("executed"); 
Console.ReadLine(); 

请参阅Circular Dependency in constructors and Dependency Injection关于如何重构类以移除循环引用

相关问题