如何在C#中访问父对象 [英] How to access to the parent object in c#
本文介绍了如何在C#中访问父对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个仪表"课程. 仪表"的一个属性是称为生产"的另一类. 我需要通过 引用 从生产类访问电表类(功率额定值)的属性.在Meter的实例化时,powerRating未知.
I have a "meter" class. One property of "meter" is another class called "production". I need to access to a property of meter class (power rating) from production class by reference. The powerRating is not known at the instantiation of Meter.
我该怎么做?
预先感谢
public class Meter
{
private int _powerRating = 0;
private Production _production;
public Meter()
{
_production = new Production();
}
}
推荐答案
将对仪表实例的引用存储为Production中的成员:
Store a reference to the meter instance as a member in 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成员.
Also note that you need to implement an accessor method/property so that the Production class can actually access the powerRating member of the Meter class.
这篇关于如何在C#中访问父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文