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 1890
旧时难觅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:45

    The first thing that struck me with this scenario is that there is definite feature envy between ItemCollection and Item. I understand your desire to make adding the child item to the collection and setting the parent to be an autonomous operation, but really I think the responsibility of maintaining that relationship is in the Item, not the ItemCollection.

    I would recommend exposing the ChildItems on Item as a Read-Only collection (with IEnumerable perhaps), and putting the AddChild(Item child),RemoveChild(Item child), ClearChildren(), etc methods on the Item. That puts the responsibility for maintaining the Parent with the Item where you don't have concerns leaking into other classes.

提交回复
热议问题