如何在 Dart 中创建我们自己的元数据? [英] How to create our own metadata in Dart?

查看:26
本文介绍了如何在 Dart 中创建我们自己的元数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的 dart 编码器创建一些自己的元数据,例如@table,@column,但我找不到任何有用的文档.

I want to create some own metadata for my dart codem, e.g. @table, @column, but I can't find any useful documents about it.

但我确实发现 angular.dart 中有一些特殊的元数据(例如 NgController):https://github.com/angular/angular.dart/blob/master/demo/todo/web/todo.dart#L52

But I do found there are some special metadata (e.g. NgController) in angular.dart: https://github.com/angular/angular.dart/blob/master/demo/todo/web/todo.dart#L52

如何在 Dart 中创建我自己的元数据?有文件吗?

How to create my own metadata in Dart? Is there any documents?

推荐答案

Dart 支持用于将用户定义的注释附加到程序结构的元数据.

Dart supports metadata which is used to attach user defined annotations to program structures.

元数据由一系列注释组成,每个注释都以字符@ 开头,后跟以标识符开头的常量表达式.如果表达式不是以下之一,则为编译时错误:

Metadata consists of a series of annotations, each of which begin with the character @, followed a constant expression that starts with an identifier. It is a compile time error if the expression is not one of the following:

  1. 对编译时常量变量的引用.
  2. 对常量构造函数的调用.

元数据可以出现在库、部分标题、类、typedef、类型参数、构造函数、工厂、函数、字段、参数或变量声明之前以及导入、导出或部分指令之前.

Metadata can appear before a library, part header, class, typedef, type parameter, constructor, factory, function, field, parameter, or variable declaration and before an import, export or part directive.

因此,您建议的常量如 @table@column 受功能限制,因为它们不能保存附加信息(参数).

So, suggested by you constants such @table, @column are very limited by functionality because they cannot hold additional information (parameters).

@DataTable("sale_orders")
class SaleOrder {
  @DataColumn("sale_order_date")
  DateTime date;
}

@table
class Product {
  @column
  String name;
}

const DataColumn column = const DataColumn();

const DataTable table = const DataTable();

class DataTable {
  final String name;

  const DataTable([this.name]);
}

class DataColumn {
  final String name;

  const DataColumn([this.name]);
}

但无论如何,您可以选择最适合您需求的选项.

But in any case, you choose the option that best suits your needs.

这篇关于如何在 Dart 中创建我们自己的元数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆