从通用约束 Dart 调用静态方法 [英] Calling a static method from a generic constraint Dart

查看:23
本文介绍了从通用约束 Dart 调用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我收到的泛型类型调用静态方法.这可能吗?

I'm trying to call a static method from a generic type I receive. Is that even possible?

此外,我应用了类型约束,以便仅从其父类操作对象.

Furthermore, I apply a Type constraint in order to only manipulate the object from its parent class.

以下是我要实现的目标的简短示例:

Here is a short example of what I'm trying to achieve:

class A {
  static func() {
    print("A");
  }
}

class B extends A {
  static func() {
    print("B");
  }
}

concret<T extends A>() {
  T.func(); // I expected a print('B')
}

main() {
    concret<B>();
}

推荐答案

不,这不可能.

Dart 静态方法调用在编译时解析,因此不可能在只有运行时有值的类型变量上调用它们.

Dart static method invocations are resolved at compile-time, so it's not possible to call them on type variables which only have a value at run-time.

如果有可能,那将是完全不安全的.任何人都可以创建一个扩展 A 的类 C,它没有静态 func 成员并调用 concret();.由于静态成员不是继承的,它必须给您一个运行时错误,并且您无法在编译时检测到该错误.这是不允许的主要原因.

If it was possible, it would be completely unsafe. Anyone can create a class C extending A which does not have a static func member and invoke concret<C>();. Since static members are not inherited, it would have to give you a run-time error, and there is nothing you can do to detect that at compile-time. That is the primary reason why it is not allowed.

这篇关于从通用约束 Dart 调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆