gpt4 book ai didi

dart - 如何 typedef 泛型函数?

转载 作者:行者123 更新时间:2023-12-05 00:12:19 27 4
gpt4 key购买 nike

我有一个看起来像这样的通用静态方法:

static build<K>() {
return (GenericClass<K> param) => MyClass<K>(param);
}

到目前为止,我已经尝试过:
typedef F = MyClass<K> Function(GenericClass<K> param);

但它说:

The return type '(GenericClass<K>) → MyClass<K>' isn't a '(GenericClass<dynamic>) → MyClass<dynamic>', as defined by the method 'build'.




typedef F = SimpleViewModel<K> Function<k>(Store<K> param);

其中说:

The return type '(GenericClass<K>) → MyClass<K>' isn't a '<K>(GenericClass<K>) → MyClass<K>', as defined by the method 'build'.


MyClass看起来像这样:
class MyClass<T> {
final GenericClass<T> param;

MyClass(this.param);


static build<K>() {
return (GenericClass<K> param) => MyClass<K>(param);
}
}

那么,什么是有效的 typedef为了它?

最佳答案

当涉及到 typedef 时,有两个“通用”概念。 typedef 可以是一个类型的泛型,或者 typedef 可以引用一个泛型函数(或两者):

T 上通用的 typedef :

typedef F<T> = T Function(T);

然后在使用中:
F first = (dynamic arg) => arg; // F means F<dynamic>
F<String> second = (String arg) => arg; // F<String> means both T must be String

引用 M 上的泛型函数的 typedef :
typedef F = M Function<M>(M);

然后在使用中:
F first = <M>(M arg) => arg; // The anonymous function is defined as generic
// F<String> -> Illegal, F has no generic argument
// F second = (String arg) => arg -> Illegal, the anonymous function is not generic

或两者:
typedef F<T> = M Function<M>(T,M);

并在使用中:
F first = <M>(dynamic arg1, M arg2) => arg2; // F means F<dynamic> so the T must be dynamic
F<String second = <M>(String arg1, M arg2) => arg2; // The T must be String, the function must still be generic on the second arg and return type

关于dart - 如何 typedef 泛型函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51092028/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com