How to access to the parent object in c#

后端 未结 7 856
难免孤独
难免孤独 2020-12-14 06:28

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 clas

7条回答
  •  清歌不尽
    2020-12-14 06:55

    Why not change the constructor on Production to let you pass in a reference at construction time:

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

    In the Production constructor you can assign this to a private field or a property. Then Production will always have access to is parent.

提交回复
热议问题