如何在Dart中创建通用方法? [英] How to create a generic method in Dart?
问题描述
我正在尝试在Dart(1.22.0-dev.10.3)中使用通用方法。这是一个简单的示例:
I'm trying to use generic methods in Dart (1.22.0-dev.10.3). Here is a simple example:
abstract class VR<T> {
VR();
bool foo<T>(T value);
}
class VRInt extends VR<int> {
VRInt();
bool foo<int>(int n) => n > 0; // Thinks n is Object
}
class VRString extends VR<String> {
VRString();
bool foo<String>(String s) => s.length > 0; // Thinks s is Object
}
两个子类均生成错误,该错误表示 foo
是一个对象。
Both subclasses generate errors that say the argument to foo
is an Object.
我确定这只是语法错误,但是我已经在文档中搜索并找不到答案。
I'm sure this is just a syntactic error on my part, but I've searched the documentation and can't find an answer.
推荐答案
在引入通用方法之前,您已经可以完成您的工作了,因为您只是在使用类的泛型类型参数。
为此,只需删除方法中的类型参数即可解决问题。
What you are doing could be done already before generic methods were introduced because you're just using the generic type parameter of the class. For this purpose just remove the type parameters on the methods to fix the problem.
泛型方法允许传递专门用于方法的类型,而不是调用站点
Generic methods are to allow to pass a type that specializes a method no the call site
class MyClass {
T myMethod<T>(T param) {
prinz(param);
}
}
然后像这样使用它
new MyClass().myMethod<List<String>>(['a', 'b', 'c']);
这篇关于如何在Dart中创建通用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!