简体   繁体   English

generics 无法在 dart/flutter 中使用超类的函数

[英]generics not able to use functions of superclass in dart/flutter

I have a problem with the syntax in Dart. I want to be able to use a constructor on a generic class. So I let the generic class extend an abstract class which has the specified constructor.我对 Dart 中的语法有疑问。我希望能够在泛型 class 上使用构造函数。所以我让泛型 class 扩展具有指定构造函数的抽象 class。 But the Code still shows me that it's not working.但是代码仍然告诉我它不起作用。 Does anyone have an idea?有人有想法吗?

T fetchItem<T extends JsonModel>(){
    return T.fromJson(); 
    // This line shows the error 
    // The method 'fromJson' isn't defined for the type 'Type'.
  }

abstract class JsonModel {
  JsonModel.fromJson();
}

The following solution works, but I think it's extremly ugly:以下解决方案有效,但我认为它非常难看:

T fetchItem<T extends JsonModel<T>>(T t){
    return t.fromJson();
  }

abstract class JsonModel<T> {
  T fromJson();
}

Constructors are not inherited.构造函数不被继承。 Just because a base class has a certain constructor, does not mean the derived class has that constructor.仅仅因为基类 class 具有特定的构造函数,并不意味着派生的 class 具有该构造函数。

It doesn't have anything to do with generics. If you extended a class X from your JsonModel, it simply would not have a constructor of that name.它与 generics 没有任何关系。如果您从 JsonModel 扩展了一个 class X,它根本就不会有该名称的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM