避免循环引用

发布于 2024-12-20 03:52:11 字数 619 浏览 1 评论 0原文

我有一个类 Form,它保存 Question 项的哈希值。

class Form
{
    Dictionary < int , Answer> listOfQuestions;
}

class Question
{
    int questionId = 2;
    int dependsOnQuestion = 1;
    string answer;
    public bool IsDependancyMet() {/*problem*/}
}

我希望一个问题依赖于另一个问题的答案,例如,如果问题 1 的答案是“已婚”,则显示问题 2,否则,不显示它。

实施该方法的正确方法是什么?

是否会将 Form 实例的引用添加到问题实例中,以便让后者访问问题的哈希。虽然我不喜欢。

另一种方法是向 Form 类添加一个方法,该方法接收问题 ID 并检查是否满足其所有依赖项,但话又说回来,问题应该知道表单实例。

底线: 谁应该检查依赖关系以及如何检查,以使系统模块化并使每个类尽可能少地了解其环境?或者至少避免循环引用。

提前致谢。

I have a class Form, which holds a hash of Question items.

class Form
{
    Dictionary < int , Answer> listOfQuestions;
}

class Question
{
    int questionId = 2;
    int dependsOnQuestion = 1;
    string answer;
    public bool IsDependancyMet() {/*problem*/}
}

I want a single Question to depend on an answer of another question, say, if the answer to question 1 is "Married", display question 2, otherwise, don't display it.

What would be the proper way of implementing that?

Would that be adding of a reference of the Form instance to the question instance, to let the later one access to the hash of questions. Though I don't like it.

The other way is to add a method to the Form class, which receives an question ID and checks whether all it's dependencies are met, but then again, the question should be aware of the form instance.

ON the bottom line:
Who should check the dependencies and how, to leave the system modular and each class the less aware of it's environment as possible? Or at least avoid cycle referencing.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没企图 2024-12-27 03:52:11

类似于

class Form
{
    Dictionary < int , Answer> listOfQuestions;
    int firstQuestion;

    public void NextQuestion() {
       // ... cycle through `listOfQuestions` looking for a question
       // whose dependencies are fullfilled and ask it.
    }
}

class Question
{
    // ...
    public List<int> GetDependencies();
    public void Ask();
    // ...
}

Form 的东西会跟踪全局“提问”状态,而各个问题只知道它们的直接依赖关系。对我来说,这似乎是一种相对干净的方法。

What about something along the lines of

class Form
{
    Dictionary < int , Answer> listOfQuestions;
    int firstQuestion;

    public void NextQuestion() {
       // ... cycle through `listOfQuestions` looking for a question
       // whose dependencies are fullfilled and ask it.
    }
}

class Question
{
    // ...
    public List<int> GetDependencies();
    public void Ask();
    // ...
}

Form keeps track of the global 'questioning' state, while individual questions only have knowledge of their direct dependencies. To me, this seems like a relatively clean approach.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文