作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
鉴于有一些事情是这样的:
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 Bar 或 is 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/
我是一名优秀的程序员,十分优秀!