How to access to the parent object in c#

后端 未结 7 815
难免孤独
难免孤独 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 07:06

    I wouldn't reference the parent directly in the child objects. In my opinion the childs shouldn't know anything about the parents. This will limits the flexibility!

    I would solve this with events/handlers.

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

    In this case I solved it with the Func<> generic, but can be done with 'normal' functions. This why the child(Production) is totally independent from it's parent(Meter).


    But! If there are too many events/handlers or you just want to pass a parent object, i would solve it with an interface:

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

    This looks pretty much the same as the solution mentions, but the interface could be defined in another assembly and can be implemented by more than 1 class.


    Regards, Jeroen van Langen.

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