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

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

问题描述

我试图找到一种在通用类型上调用方法的方法。

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

我可以迅速写成这样:

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'.
}

代码给出错误方法'createOne'不是't为类'Type'定义。
如何解决此问题?如果可能的话,将节省大量时间和大量代码行。

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

您不能仅依靠类型变量

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

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