【问题标题】:Best method of creating two classes that have the same variables, but with different access methods创建两个具有相同变量但具有不同访问方法的类的最佳方法
【发布时间】:2020-07-31 18:46:35
【问题描述】:

我知道,通过扩展一个类,您可以创建一个可以访问其父类的所有变量和方法的子类。然而,我想要实现的是一个具有许多必需变量的类,这些变量都可以从编辑器窗口编辑;另一个具有所有这些相同的变量,但有一些不可编辑,而是具有默认值。

我的具体示例是一个包含许多公共变量的对话类:

public class Dialogue : MonoBehaviour
{
    // Public variables for determining whether the dialogue has automatic or manual triggering; and whether it's single use
    public bool isAutomatic, isSingleUse;

    // Public variables for determining whether an unlocked discovery is required in order to trigger the dialogue at all
    public bool requiresDiscovery;
    public string requiresDiscoveryType;
    public int requiresDiscoveryId;

    // Public lists for general conversations and default topic sentences
    public List<Conversation> generalConversations;
    public List<Sentence> defaultTopicSentences;

    // Public variable for holding the optional topics in our conversation (can be left empty if desired)
    public List<Topic> topics;

    /* Methods here... */

}

上面的类用于对话事件和过场动画事件(可以包含多个对话与角色移动和其他更复杂的东西)。它非常适合对话事件,但我可以创建一个变体类,其中一些变量(例如 isAutomatic、isSingleUse、requiresDiscovery 等)自动设置为 false,而在编辑器中没有更改它们的选项。这是因为某些变量与过场动画事件无关,如果设置为 true,可能会导致问题。

我遇到的问题是我是否可以使用 Dialogue 作为父类并以某种方式覆盖子类中某些变量的公共访问;或者如果有另一种方法必须这样做。如果有人能给我一个代码示例,说明我如何实现上述目标,那将非常有帮助。

提前致谢。

【问题讨论】:

  • 看起来几乎像一个 X/Y 问题类型的问题。您似乎违反了单一职责原则。如果您有一个处理对话的课程和一个处理过场动画的课程,那么这首先不是问题。
  • 嗯,你可能正在做一些事情......你有没有机会建议一个通用的对话父类,然后是单个对话事件的子类和过场动画的单独子类?
  • 过场动画在什么方面是一种对话?你甚至声明can contain multiple dialogues with character movements and other more
  • 对不起,我可能没有正确描述这种情况。我有一个 DialogueController 可以传递上述 Dialogue 类的单个实例。我的过场动画由 CutsceneController 类控制,该类可以传递许多 Dialogue 实例并按顺序运行。 CutsceneController 本身每次运行 Dialogue 实例时都会调用 DialogueController(以及做很多其他事情)。所以我的意思是有一个 Dialogue 的子类直接传递给 DialogueController 和一个单独的子类传递给 CutsceneController。
  • 你所描述的听起来不错,到底是什么问题?如果具有适用于两者的共同属性,则使其成为每个的抽象父级,但它本身不是对话或过场动画事件。只有适用于每种情况的公共属性属于每个子类。

标签: c# class oop unity3d inheritance


【解决方案1】:

坚持继承,否则你要么在两个类中出现具有相同属性的代码重复,要么试图将一个类拼凑在一起用于两种用途,这与 SRP 背道而驰。将它们分开会让您的生活更轻松。

通过这样做,您将能够在过场动画中拥有多个对话类,但仍然具有过场动画中对话的功能。

创建一个名为Cutscene 的新类,并在创建Cutscene 的新实例时设置您需要的任何Dialogue 变量。

public class Cutscene : Dialogue
{
     // Set whatever you need to false to prevent any issues
     public Cutscene() {
          this.isAutomatic = false;
          this.isSingleUse = false;
          this.requiresDiscovery = false
          // etc...
     }
}

如果你想了解更多关于继承的知识,MSDN has a great page on it

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多