dart - @ 在 Dart 程序中做什么?

标签 dart metadata

我刚刚花了 20 个小时学习 Dart 语言的基础知识,但是当我在开源 Dart 程序中发现 @ 前缀(例如 here )时,我发现大多数程序使用,我想知道 @ 指令在这些程序中做什么...

供您引用,the official documentation says the following:

Metadata Use metadata to give additional information about your code. A metadata annotation begins with the character @, followed by either a reference to a compile-time constant (such as deprecated) or a call to a constant constructor. Three annotations are available to all Dart code: @deprecated, @override, and @proxy. For examples of using @override and @proxy, see the section called “Extending a Class”. Here’s an example of using the @deprecated annotation:

但是,@ 指令向代码中添加了哪些“附加信息”?如果通过编写以下构造函数来创建实例

@todo('seth', 'make this do something')

,而不是以下默认构造函数:

todo('seth", 'make this do something')

,我可以从第一个构造函数中得到什么好处?

我知道使用内置元数据(例如 @deprecated@override)可以给我带来在运行应用程序时收到警告的优势,但是什么我可以从自定义 @todo 上的案例或上述 Github 上链接的示例代码中获取吗?

最佳答案

注释可以通过 dart:mirrors 访问图书馆。每当您想要提供有关类、方法等的附加信息时,您都可以使用自定义注释。例如 @MirrorsUsed用于向 dart2js 编译器提供额外信息,以优化生成的 JavaScript 的大小。

注释通常对框架或库作者比应用程序作者更有用。例如,如果您在 Dart 中创建 REST 服务器框架,则可以使用注释将方法转换为 Web 资源。例如,它可能类似于以下内容(假设您已创建 @GET 注释):

@GET('/users/')
List<User> getUsers() {
 // ...
}

然后,您可以让框架在服务器启动时使用镜像扫描代码,以查找带有 @GET 注释的所有方法,并将该方法绑定(bind)到注释中指定的 URL。

关于dart - @ 在 Dart 程序中做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23476800/

相关文章:

dart - 我需要在使用之前将我的 Dart 包发布到 pub.dartlang.org 吗?

Dart:将列表列表的字符串表示形式转换为列表列表

flutter - 为什么 Flutter 中的网络请求不会阻塞 UI

firebase - Flutter/Dart- 'List<DropdownMenuItem<dynamic>>'类型不是'List <DropdownMenuItem <String >>类型的子类型

javascript - 显示 USGS 地震 JSON 数据的元数据

RSS 作为没有网络存在的元数据?

kubernetes 如何在 pod 中获取集群域(例如 svc.cluster.local)?

dart - 是否可以使用 flutter dart 构建并排功能比较表?如何?

java - 加载带有 exif 和/或损坏的元数据的 jpeg 图像

postgresql - 从 PostgreSQL 数据库中检索评论