我不会直接在子对象中引用父对象。在我看来,孩子不应该知道父母的任何事情。这将限制灵活性!
我会用事件/处理程序解决这个问题。
public class Meter
{
private int _powerRating = 0;
private Production _production;
public Meter()
{
_production = new Production();
_production.OnRequestPowerRating += new Func<int>(delegate { return _powerRating; });
_production.DoSomething();
}
}
public class Production
{
protected int RequestPowerRating()
{
if (OnRequestPowerRating == null)
throw new Exception("OnRequestPowerRating handler is not assigned");
return OnRequestPowerRating();
}
public void DoSomething()
{
int powerRating = RequestPowerRating();
Debug.WriteLine("The parents powerrating is :" + powerRating);
}
public Func<int> OnRequestPowerRating;
}
在这种情况下,我使用 Func<> 泛型解决了它,但可以使用“普通”函数来完成。这就是为什么孩子(生产)完全独立于它的父母(仪表)。
但!如果事件/处理程序太多,或者您只想传递父对象,我将使用接口解决它:
public interface IMeter
{
int PowerRating { get; }
}
public class Meter : IMeter
{
private int _powerRating = 0;
private Production _production;
public Meter()
{
_production = new Production(this);
_production.DoSomething();
}
public int PowerRating { get { return _powerRating; } }
}
public class Production
{
private IMeter _meter;
public Production(IMeter meter)
{
_meter = meter;
}
public void DoSomething()
{
Debug.WriteLine("The parents powerrating is :" + _meter.PowerRating);
}
}
这看起来与解决方案提到的几乎相同,但接口可以在另一个程序集中定义,并且可以由多个类实现。
问候,杰伦·范·朗根。