views:

168

answers:

2

Hello,

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

A: 

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.

Marc Gravell
I was also thinking about the constructor, but the class metadata contains only a default constructor.You must be right about the internal setter. Thanks.
noon
A: 

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.

Nate Heinrich
It must be internal indeed.For controls in winform, the setter of the Parent property is public :public Control Parent { get; set; }Thanks
noon