繁体   English   中英

Dart type_test_with_non_type 在变量中存储类型时

[英]Dart type_test_with_non_type when storing type in variable

在我的 Flutter 应用程序中,我想构建这个 function:

bool isValidType(element, Type cls) {
  return element is cls;
}

问题是: The name 'cls' isn't a type and can't be used in an 'is' expression. Try correcting the name to match an existing type. dart(type_test_with_non_type) The name 'cls' isn't a type and can't be used in an 'is' expression. Try correcting the name to match an existing type. dart(type_test_with_non_type)

element是动态的,但我希望它是 class 的 Object 扩展 class Element (如class Node extends Element )。 我希望能够使用这个 function 的方式是:

isValidType(node, Node) -> true
isValidType(node, Element) -> true

我首先想到我可以这样做:

bool isValidType(element, Type cls) {
  return element.runtimeType == cls;
}

但问题在于,对于上面提供的示例,它返回以下内容:

isValidType(node, Node) -> true
isValidType(node, Element) -> false

原因当然是noderuntimeTypeNode而不是Element

我必须更改首先提供的 function 中的哪些内容才能满足我的要求?

目前您无法使用 object Type做很多事情。一般建议是避免使用它们。

在您的情况下,如果您想检查编译时已知的类型,您可以将isValidType改为通用的 function :

bool isValidType<T>(dynamic element) => element is T;

然后使用isValidType<Node>(node)isValidType<Element>(node) 但是,我认为这样的 function 不会增加任何内容,因此您不妨在调用站点将isValidType<Node>(Node)替换为node is Node

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM