Maintaining a two way relationship between classes

前端 未结 6 602
萌比男神i
萌比男神i 2021-02-02 00:34

It is pretty common, especially in applications with an ORM, to have a two way mapping between classes. Like this:

public class Product
{
    private List

        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-02 01:19

    In the past, I've done something like this when I needed to maintain this type of relationship...

    public class Owner
    {
        public List OwnedList { get; set; }
    }
    
    public class Owned
    {
        private Owner _owner;
    
        public Owner ParentOwner
        {
            get
            {
                if ( _owner == null )
                    _owner = GetParentOwner(); // GetParentOwner() can be any method for getting the parent object
                return _owner;
            }
        }
    }
    

提交回复
热议问题