In C# 4.0, is there any way to make an otherwise private member of one class available only to a specific other class?

前端 未结 9 1892
旧时难觅i
旧时难觅i 2021-01-31 19:27

We\'re creating an object hierarchy where each item has a collection of other items, and each item also has a Parent property pointing to its parent item. Pretty st

9条回答
  •  梦谈多话
    2021-01-31 19:44

    My answer is built off of two parts

    1. Why is it so "Unsafe" to have the Interface ISetParent?

    private/internal access modifiers are ment to prevent from mistakes, not really "Secure Code".

    Remember... you can call private methods using some Reflections/Invoke Etc...

    .

    2 . i usually make everything public and make sure both sides know how to handle each other,

    ofcourse, there is a little ping-pong but it takes just few cycles (in this case i have a NamedSet)

        private IPhysicalObject partOf;
        public IPhysicalObject PartOf
        {
            get { return partOf; }
            set
            {
                if (partOf != value)
                {
                    if (partOf != null)
                        partOf.Children.Remove(this.Designation);
    
                    partOf = value;
    
                    if (partOf != null)
                        partOf.Children.Add(this.Designation);
                }
            }
        }
    
        public virtual void Add(String key, IPhysicalObject value)
        {
            IPhysicalObject o;
            if (!TryGetValue(key, out o))
            {
                innerDictionary.Add(key, value);
                value.PartOf = Parent;
            }
        }
    
        public virtual bool Remove(String key)
        {
            IPhysicalObject o;
            if(TryGetValue(key, out o))
            {
                innerDictionary.Remove(key);
                o.PartOf = null;
            }
        }
    

    Hope this helps... Good Day, Tomer W.

    P.S. I'll never get how this Editor is working... should i HTML it, or should i not?

提交回复
热议问题