仿制药无法在飞镖/扑朔迷离中使用超类的功能

发布于 2025-02-06 08:30:01 字数 522 浏览 2 评论 0原文

我对飞镖的语法有问题。我希望能够在通用类上使用构造函数。因此,我让通用类扩展一个具有指定构造函数的抽象类。但是代码仍然向我表明它不起作用。有人有主意吗?

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();
}

以下解决方案有效,但我认为这非常丑陋:

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

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

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. 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();
}

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

断爱 2025-02-13 08:30:06

构造函数没有继承。仅仅因为基类具有某个构造函数,并不意味着派生类具有该构造函数。

它与仿制药无关。如果您从JSONMODEL扩展了X类,则根本没有该名称的构造函数。

Constructors are not inherited. Just because a base class has a certain constructor, does not mean the derived class has that constructor.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文