我有一个“仪表”类。 “仪表”的一个属性是称为“生产”的另一类。我需要通过reference从生产类访问仪表类的属性(额定功率)。在Meter的实例处,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;
}
}
然后在仪表类中:
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<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);
}
}
这看起来与解决方案中提到的几乎相同,但是接口可以在另一个程序集中定义,并且可以由多个类实现。
关于,Jeroen van Langen。
您需要在Production类中添加一个属性,并将其设置为指向其父级,默认情况下不存在。
为什么不更改Production
上的构造函数以让您在构造时传递引用:
public class Meter
{
private int _powerRating = 0;
private Production _production;
public Meter()
{
_production = new Production(this);
}
}
在Production
构造函数中,您可以将其分配给私有字段或属性。然后,Production
将始终可以访问父级。
您可能在生产对象中添加了一个名为'SetPowerRating(int)'的方法,该方法可以在Production中设置一个属性,然后在Meter对象中调用此方法,然后再在Production对象中使用该属性?
我会给父母一个ID,并将parentID存储在子对象中,这样您就可以根据需要提取有关父母的信息,而无需创建parent-owns-child / child-owns-parent循环。
类似这样:
public int PowerRating
{
get { return base.PowerRating; } // if power inherits from meter...
}