I have the following problem. This is a 开发者_StackOverflowsimple example of some classes I have (each have dependencies on other classes).
public Class1()
{
public Class1(Class2 class2)
{
}
}
public Class2()
{
public Class2(Class3 class3)
{
}
}
public Class3()
{
public Class1 class1;
public Class3(Class1 class1)
{
this.class1 = class1;
}
}
I then have the following code initialising the objects.
Class1 class1 = null;
Class2 class2 = null;
Class3 class3 = null;
class3 = new Class3(class1);
class2 = new Class2(class3);
class1 = new Class1(class2);
Assert.IsNotNull(class3.class1)
The problem I have is that the assert is always null, even though class1 has been initalized. One condition I do have is that I only want there to be one instance of each class created.
Can anybody advise the best way to make sure the assert passes.
class1 is not initialized to its object when class3 is created, thus class3's instance of it is null.
The proper way to make this test pass is:
Class1 class1 = null;
Class2 class2 = null;
Class3 class3 = null;
class1 = new Class1();
class3 = new Class3(class1);
class2 = new Class2(class3);
class1.Class3 = class3;
Assert.IsNotNull(class3.class1)
class1
is null when you call:
class3 = new Class3(class1);
So naturally the assertion fails. You need to instantiate class1 before you attempt to pass it to the Class3
constructor.
Now, that's not trivial to achieve since you have circular references. What you need to do therefore is create the objects first, and then fix up the references. Decouple the construction from the assignment of the references to the other objects.
What's more, you should not name object instances class
, since they are objects rather than classes. The distinction is important.
Initially the class1 variable is a null pointer. Then you assign it some value and the reference changes. But the class3.class1 still points to null.
you need to make sure that the reference does not change, but the value it points to changes.
精彩评论