How to access to the parent object in c#

后端 未结 7 814
难免孤独
难免孤独 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:40

    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;
      }
    }
    

    And then in the Meter-class:

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

    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.

    0 讨论(0)
  • 2020-12-14 06:43

    I would give the parent an ID, and store the parentID in the child object, so that you can pull information about the parent as needed without creating a parent-owns-child/child-owns-parent loop.

    0 讨论(0)
  • 2020-12-14 06:49

    something like this:

      public int PowerRating
        {
           get { return base.PowerRating; } // if power inherits from meter...
        }
    
    0 讨论(0)
  • 2020-12-14 06:55

    You would need to add a property to your Production class and set it to point back at its parent, this doesn't exist by default.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-14 06:57

    You could maybe add a method to your Production object called 'SetPowerRating(int)' which sets a property in Production, and call this in your Meter object before using the property in the Production object?

    0 讨论(0)
提交回复
热议问题