泛型类型 Dart 上的调用方法 [英] Calling method on generic type Dart

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

问题描述

我试图找到一种方法来调用泛型类型的方法.但是找不到.

I am trying to get a way to call method on a generic type. But can't find it.

在 swift 中,我可以这样写:

In swift I can write like:

protocol SomeGeneric {
    static func createOne() -> Self
    func doSomething()

}

class Foo: SomeGeneric {
    required init() {

    }
    static func createOne() -> Self {
        return self.init()
    }

    func doSomething() {
        print("Hey this is fooooo")
    }
}

class Bar: SomeGeneric {
    required init() {

    }

    static func createOne() -> Self {
        return self.init()
    }

    func doSomething() {
        print("Hey this is barrrrrrr")
    }
}

func create<T: SomeGeneric>() -> T {
    return T.createOne()
}

let foo: Foo = create()
let bar: Bar = create()

foo.doSomething() //prints  Hey this is fooooo
bar.doSomething() //prints  Hey this is barrrrrrr

在 Dart 中我尝试过:

In Dart I tried:

abstract class SomeGeneric {
  SomeGeneric createOne();
  void doSomething();
}

class Foo extends SomeGeneric {
  @override
  SomeGeneric createOne() {
    return Foo();
  }

  @override
  void doSomething() {
    print("Hey this is fooooo");
  }
}

class Bar extends SomeGeneric {
  @override
  SomeGeneric createOne() {
    return Bar();
  }

  @override
  void doSomething() {
    print("Hey this is barrrrr");
  }
}

T create<T extends SomeGeneric>() {
  return T.createOne();//error: The method 'createOne' isn't defined for the class 'Type'.
}

代码给出错误未为类Type"定义方法createOne"如何解决这个问题?.如果这是可能的,它将节省大量时间和大量代码行.

The code gives error The method 'createOne' isn't defined for the class 'Type' How to fix this?. If this is possible, it would save lot of time and tons of lines of code.

推荐答案

这是不可能的.在 Dart 中,您不能通过类型变量调用静态方法,因为静态方法必须在编译时解析,而类型变量直到运行时才具有值.Dart 接口不是 Swift 协议,它们只能指定实例方法.

It is not possible. In Dart you cannot call static methods through a type-variable because static methods must be resolved at compile-time and type-variables do not have a value until run-time. Dart interfaces are not Swift protocols, they can only specify instance methods.

如果你想参数化一个能够创建一个新类型对象的类,你需要传递一个函数来这样做:

If you want to parameterize a class with the ability to create a new object of a type, you need to pass a function doing so:

void floo<T>(T create(), ...) { 
   ...
   T t = create();
   ...
}

您不能单独依赖类型变量.

You cannot rely on the type variable alone for that.

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

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