gpt4 book ai didi

flutter - 我怎样才能避免 Dart 中这种不必要的转换?

转载 作者:IT王子 更新时间:2023-10-29 07:11:10 24 4
gpt4 key购买 nike

鉴于有一些事情是这样的:

class Foo {}
class Bar extends Foo {}
class Baz extends Foo {}

我发现自己在写这种类型的代码:

if (foo is Bar) {
(foo as Bar).doSomething(); //Compiler warning of unnecessary cast.
} else (foo is Baz) {
(foo as Bar).doSomething(); //Compiler warning of unnecessary cast.
}

我不知道如何避免这种情况。

如果我在转换之前删除了 is Baris Baz 的检查类型,我可能会遇到运行时错误,如果我不转换,则意味着没有访问该类型的公共(public)内容。

也许我遵循了一个需要更新的有缺陷的代码设计,因为我相信我应该避免检查类类型。

Dart 中有什么方法可以帮助解决这个问题吗?

(foo as? Bar)?.doSomething()(像 swift 一样)

最佳答案

实际上你可以只做 foo.doSomething(); 而不是 (foo as Bar).doSomething()。编译器知道如果条件 if(foo is Bar) 结果为真,则该代码块中的变量 foo 的类型为 Bar.

尝试:

if (foo is Bar) {
foo.doSomething(); // It's automatically inferred that type of `foo` is `Bar`
} else if (foo is Baz) {
foo.doSomething(); // It's automatically inferred that type of `foo` is `Baz`
}

希望对您有所帮助!

关于flutter - 我怎样才能避免 Dart 中这种不必要的转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56735584/

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