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 1882
旧时难觅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:58

    C# Doesn't have a friend keyword, but it has something close called internal. You could mark the methods you want to expose in a limited fashion as internal and then only other types in that assembly will be able to see them. If all your code is in one assembly, this won't help you much, but if this class is packaged in a separate assembly it would work.

    public class Item
    {
        public string Name{ get; set; }
        public Item Parent{ get; internal set; } // changed to internal...
        public ItemsCollection ChildItems;
    
        public Item()
        {
            this.ChildItems = new ItemsCollection (this);
        }
    }
    

提交回复
热议问题