
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
5.5 方法类型定义
在Dart编程语言中,一切皆对象,方法也不例外。下面来看一段代码:


在代码中,我们把exampleFunction赋值为test,在此过程中,String类型信息丢失了。如果想保留类型信息的话,就可以使用方法类型定义(typedef)来改写上述代码。保留类型信息的好处是可以使代码更易读,而且一些IDE的代码检查工具也可以检测出相关的问题,避免异常发生。具体改写的方法如下:

运行后,没有错误发生。在开始将一个方法定义为StringOutput之后,就可以使用断言来判断是否是该方法类型。在上例中,如果存在其他的方法并定义为相应的名称,那么当再次使用断言时便会提示出错:

运行结果:

