如何通过依赖关系创建适当的继承?

发布于 2025-02-05 16:41:10 字数 1379 浏览 3 评论 0原文

在从事我的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文