抽象类/接口中的静态方法访问(flutter/dart)

发布于 2025-01-21 16:06:44 字数 629 浏览 3 评论 0原文

在我的Flutter项目中,我有以下抽象类。

abstract class Storage {
  static method1{}
  static method2{}
  ...
}

然后,我定义了扩展到存储的其他类,但是每个子类都实现了存储类中定义的某些方法(带有空白)。

class StorageA{
    static method1{ print("1") }
}
class StorageB{
    static method2{ print("2") }
}

我的目标是通过使用存储名称空间来调用这些静态方法中的任何一种,但是,我想调用子类中的超层方法。例如,当我调用storege.method1时,它应该打印1。这是一个非常简单的示例,但我通常有很多方法,我想将这些方法分组为扩展到存储的不同类。但是与此同时,我想访问带有存储名称空间的所有覆盖方法。当前,当我进行storege.method1编译器拾取存储中定义的函数时,因为它具有空体,因此可以选择该功能。如果我删除身体并将其转换为功能声明,则无法将功能定义为静态。那么,我该如何在这里实现目标?

是否将所有内容组合到单个存储类中,并将方法定义为静态解决方案?

In my flutter project, I have the following abstract class.

abstract class Storage {
  static method1{}
  static method2{}
  ...
}

Then I define other classes that extend to Storage but each child class implements some of the methods defined (with empty body) in the Storage class.

class StorageA{
    static method1{ print("1") }
}
class StorageB{
    static method2{ print("2") }
}

My goal is to be able to call any of these static method by using the Storage namespace, however, I want to invoke the overridden methods in the child classes. For example, when I call Storage.method1 it should print 1. This is a very simplified example but I normally have bunch of methods and I want to group these methods into different classes that extend to Storage. But at the same time i want to access all the overridden methods with Storage namespace. Currently when I do Storage.method1 compiler picks up the function defined in Storage because it has an empty body. If i remove the body and turn it into function declaration, then I can't define the function as static. So, how can I reach my goal here?

Is combining everything into a single Storage class and defining the methods as static the only solution here?

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

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

发布评论

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