如何通过依赖关系创建适当的继承?
在从事我的Unity项目时,我创建了一个抽象类,并存储A将其作为一个字段。然后,我在start
上称其功能init
,以传递其所需的参考。
假设我有一个抽象的课程:
public abstract class Base : MonoBehaviour
{
protected BaseTool _baseTool; // A references that every inheritor uses
public virtual void Init(BaseTool baseTool)
{
_baseTool = baseTool;
}
... // More functuality
}
现在我将其存储为以下字段:
public class Foo : MonoBehaviour
{
[SerializeField]
private Base _base;
[SerializeField]
BaseTool _baseTool;
void Start()
{
_base.Init(_baseTool);
}
}
现在我有了一个继承者:
public class Inheritor1 : Base
{
public override Init(BaseTool baseTool)
{
base.Init(baseTool);
}
... // More functuality
}
到目前为止,一切都很好。但是,假设我现在有另一个继承机,它也对另一个工具有依赖性:
public class Inheritor2 : Base
{
private Inheritor2Tool _inheritor2Tool; // The dependency
}
这意味着,如果我想用in
senasonitor2 覆盖INIT
(因此,我将成为能够在foo
中调用init
,并初始化字段中存储的任何继承者_base
)我需要更改整个init
签名到init(basetool basetool,sashitor2tool sashitor2Tool)
同时,只有senasonitor2
将使用新的参数sasenitor2Tool sashitor2tool
。
这对我来说似乎是非常错误的,但是我不知道如何避免这种情况。 那我有什么选择?
While working on my Unity project, I created an abstract class and stored a to reference it as a field. I then called its function Init
on Start
in order to pass to it its needed references.
So let's say I have an abstract class:
public abstract class Base : MonoBehaviour
{
protected BaseTool _baseTool; // A references that every inheritor uses
public virtual void Init(BaseTool baseTool)
{
_baseTool = baseTool;
}
... // More functuality
}
Now I store it as a field as below:
public class Foo : MonoBehaviour
{
[SerializeField]
private Base _base;
[SerializeField]
BaseTool _baseTool;
void Start()
{
_base.Init(_baseTool);
}
}
And now I have an inheritor:
public class Inheritor1 : Base
{
public override Init(BaseTool baseTool)
{
base.Init(baseTool);
}
... // More functuality
}
So far everything is good. However, let's say I now have another inheritor which also has a dependency on another tool:
public class Inheritor2 : Base
{
private Inheritor2Tool _inheritor2Tool; // The dependency
}
That means, that if I want to override Init
with Inheritor2
(so I'll be able to call Init
in Foo
and initialize whatever inheritor is stored inside the field _base
) I'll need to change the whole Init
signature to Init(BaseTool baseTool, Inheritor2Tool inheritor2Tool)
meanwhile only Inheritor2
will use the new parameter Inheritor2Tool inheritor2Tool
.
That seems very wrong to me, but I don't know how I can avoid this.
So what are my options?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论