请考虑以下代码:
ButtonElement btnSend = (ButtonElement) query('#btnSendToServer');
Run Code Online (Sandbox Code Playgroud)
我收到一个内部错误:
Internal error: 'http://127.0.0.1:3030/home/Seth.Ladd/Projects/DartSimpleChat/SimpleChatClient/web/out/simplechatclient.dart': Error: line 30 pos 43: semicolon expected
ButtonElement btnSend = (ButtonElement) query('#btnSendToServer');
^
Run Code Online (Sandbox Code Playgroud)
所以问题是:
query支持显式/隐式转换?query还是我可以盲目相信那个物体会被退回ButtonElement吗?ButtonElements吗?Dart是一种动态类型语言.即使你把类型扔到各处,它仍然是动态的.因此,考虑到这一点,通常在你投射时意味着你要确定这个东西是特定类型的.
在你的情况下,你想确定它是一个ButtonElement.您可以使用is和as运算符进行类型测试:
// You can write code to test the type yourself:
if (btnSend is! ButtonElement) throw 'Not a button';
// Or you can use "as" that will throw if the type is wrong:
var btnSend = query('#btnSendToServer') as ButtonElement;
Run Code Online (Sandbox Code Playgroud)
根据具体情况,我使用is或as.通常我不使用as,因为它有(小?)性能开销.
您可以采取另一种方法,我个人更喜欢这种方法.像这样写你的代码:
ButtonElement btnSend = query('#btnSendToServer');
Run Code Online (Sandbox Code Playgroud)
在开发时,以检查模式运行:
dart --checked foo.dart
Run Code Online (Sandbox Code Playgroud)
或者当您使用Dartium时,请阅读有关使用标志手动启动Dartium的信息.我暂时没有使用Dart编辑器,所以我不确定它是否默认使用了检查模式,如果你可以改变它.
在检查模式下运行时,btnSend如果类型不匹配,则将抛出赋值.关于这一点的好处是,当您在没有选中模式的情况下在生产环境中运行代码时,您的应用程序不会受到任何性能开销的影响.
并回答一些个别问题:
query支持显式/隐式转换?不,这只是一个随意的功能,不关心类型.
ButtonElement仅搜索s?你可以这样写:
query('button#btnSendToServer')
Run Code Online (Sandbox Code Playgroud)
这是一个典型的CSS选择器,而不是Dart的东西.
ButtonElement吗?是的,不是.我相信如果对象不是a ButtonElement,它会在某个时刻抛出你的应用程序,但我会建议你在开发和编写时以检查模式运行:
ButtonElement btnSend = query('#btnSendToServer');
Run Code Online (Sandbox Code Playgroud)
由你决定要输入多少类型信息.如果你认为按钮很容易出错,那么我认为指定类型是有意义的.就个人而言,我不会对类型感到疯狂,只有我觉得它们才有意义.