Two classes with constructors such that they reference each other?
I have a feeling that this is a code smell, and I could be doing this better, and if that is the case please point it out.
class main
{
void main()
{
object A
object B
A = new SystemA(ref B)
B = new SystemB(ref A)
}
}
class Syst开发者_开发百科emA
{
SystemB B;
public SystemA (ref B)
{
this.B = B;
}
}
class SystemB
{
SystemA A;
public SystemA (ref A)
{
this.A = A;
}
}
Basically I need to initialize two classes with references to each other.
This doesn't work and generates a null reference exception for the class fields in the two child classes when they are later accessed after initialization.
I realize I could probably set these after initialization, but this adds a touch more bloat that I would like to avoid, since I view these assignments as initialization actions.
If you gave code which actually compiled, I suspect it would just end up with SystemA
storing a reference to null
- because that's the value of B
when you construct A
.
Having two classes which need a reference to each other is definitely a code smell, but you simply can't make them both refer to each other, unless one of them constructs the other and passes in "this", e.g.
class SystemA
{
private readonly SystemB systemB;
public SystemA()
{
systemB = new SystemB(this);
}
}
class SystemB
{
private readonly SystemA systemA;
public SystemB(SystemA systemA)
{
this.systemA = systemA;
}
}
Now if you need access to both values afterwards, you could either put a property in one of them giving access to the other, or (and this is really nasty) use an out
parameter in the constructor:
public SystemA(out systemB)
{
systemB = new SystemB(this);
this.systemB = systemB;
}
Then call it as:
SystemB b;
SystemA a = new SystemA(out b);
Please don't do this though.
- It's horrendously complicated
- It's generally a bad idea to let
this
escape a constructor anyway
精彩评论