我不會直接在子對象中引用父對象。在我看來,孩子們不應該對父母有任何瞭解。這會限制靈活性!
我會解決這個事件/處理程序。
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);
}
}
這看起來幾乎是相同的解決方案中提到,但接口可以定義在另一個程序集中,可以由一個以上的類實現。
Regards, Jeroen van Langen。
可能重複[什麼是從嵌套類訪問封閉類中的字段的最佳方式?](http://stackoverflow.com/questions/185124/whats-the-best-way-of-accessing-field -in-the-encl-class-from-the-nested-cl) – 2016-05-27 18:29:46
@JimFell這根本不涉及嵌套類 – Rob 2016-05-28 04:43:15