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

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

问题描述

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

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

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

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.

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

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天全站免登陆