如何在c#中访问父对象

我有一个“米”级。 “米”的一个属性是另一个叫做“生产”的类。 我需要通过参考从生产类访问米级(额定功率)的属性。 在仪表实例化时不知道powerRating。

我怎样才能做到这一点 ?

提前致谢

public class Meter { private int _powerRating = 0; private Production _production; public Meter() { _production = new Production(); } } 

将计量器实例的引用存储为生产中的成员:

 public class Production { //The other members, properties etc... private Meter m; Production(Meter m) { this.m = m; } } 

然后在Meter级:

 public class Meter { private int _powerRating = 0; private Production _production; public Meter() { _production = new Production(this); } } 

另请注意,您需要实现一个访问器方法/属性,以便Production类可以实际访问Meter类的powerRating成员。

我不会直接在子对象中引用父级。 在我看来,孩子们对父母一无所知。 这将限制灵活性!

我会用事件/处理程序解决这个问题。

 public class Meter { private int _powerRating = 0; private Production _production; public Meter() { _production = new Production(); _production.OnRequestPowerRating += new Func(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 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); } } 

这看起来与解决方案提到的几乎相同,但接口可以在另一个程序集中定义,并且可以由多个类实现。


此致,Jeroen van Langen。

您需要向Production类添加一个属性,并将其设置为指向其父级,默认情况下不存在。

为什么不在Production上更改构造函数以允许您在构造时传入引用:

 public class Meter { private int _powerRating = 0; private Production _production; public Meter() { _production = new Production(this); } } 

Production构造函数中,您可以将其分配给私有字段或属性。 然后Production将始终有权访问父母。

您可以在Production对象中添加一个名为’SetPowerRating(int)’的方法,该方法在Production中设置属性,并在使用Produ对象中的属性之前在Meter对象中调用它?

像这样的东西:

  public int PowerRating { get { return base.PowerRating; } // if power inherits from meter... }