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 1975
旧时难觅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:55

    The only two things I can think of:

    One:

    Use sort of option number 2 you mention above (which I do constantly myself)...but make the implementation of the interface (Item) be a nested private class inside of ItemsCollection... that way only ItemsCollection knows about the setter. The interface IItem only declares a getter for Parent...and no one can cast it to Item because Item is private to ItemsCollection. So, something like:

    public class ItemsCollection : ObservableCollection
    {
        private class Item : IItem 
        {
            public object Parent { get; set; }
        }
    
        private CheckParent(IItem item)
        {
            if(item.Parent != null) throw new Exception("Item already belongs to another ItemsCollection");
            ((Item)item).Parent = this.Owner; // <-- This is where we need to access the private Parent setter
        }
    
        public static IItem CreateItem() { return new Item(); }
    }
    
    public interface IItem 
    {
        object Parent {get; }
    }
    

    and when you want ItemsCollection to set the item Parent, case the IItem instance to Item (which does expose a setter). Only ItemsCollection can do this cast, since the Item implementation is private to ItemsCollection...so I think that accomplishes what you want.

    Two:

    Make it internal not private...you don't get exactly what you want, but you can use InternalsVisibleToAttribute to denote that the internal members are visible to another assembly.

提交回复
热议问题