简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM