C# 父子属性保护
这里有两个具有父/子关系的类(取自 Unity3D)
public class GameObject
{
...
public T AddComponent<T>() where T : Component;
...
}
public class Component
{
...
public GameObject gameObject { get; }
...
}
由于只有 getter 是公共的,它们如何实现设置 Component gameObject 字段的值? (Component 类中没有其他方法接受 GameObject)
我这样问是因为我使用相同类型的设计并且我想将 setter 设为私有。
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它可能有一个内部设置器,或者可能将 GameObject 传递到构造函数并在那里设置?或者它可以使用反射直接设置字段(或调用其他不可用的访问器),但我对此表示怀疑。
It could have an
internal
setter, or it could be that theGameObject
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.当您将组件添加到 GameObject 时,很可能有一个内部 setter 来分配该组件的父级 (GameObject)。因此在这种情况下,设置组件的 GameObject 的唯一方法是将组件添加到 GameObject 中。
您可以与 winForms 进行比较,如果您将子控件添加到父控件的控件集合中,则会为您设置子控件的父控件。
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.