c# parent-child property protection
Here are two classes with a parent/child relation (taken from Unity3D)
public class GameObject
{
...
public T AddComponent<T>() where T : Component;
...
}
public class Component
{
...
public GameObject gameObject { get; }
...
}
Since only the getter is public, how do they acheive to set the value开发者_运维问答 of the Component gameObject field ? (There is no other methods in the Component class that takes a GameObject)
I'm asking this because I use the same kind of design and I want to make the setter private.
Thanks
It could have an internal
setter, or it could be that the GameObject
is passed into the constructor and set there? Or it could use reflection to set the field directly (or call an otherwise unavailable accessor), but I rather doubt it.
When you add a component to the GameObject, there is most likely an internal setter that assigns the parent(GameObject) of the component. So in this case the only way to set the GameObject of a component is to add the component to the GameObject.
You could compare to winForms where if you add a child control to a parent control's control collection, the parent of the child control is set for you.
精彩评论