How and when to use the Record
type in dart and What is the difference between using it and other collection types like map, list, etc?
如何以及何时在dart中使用Record类型,以及使用它与其他集合类型(如map,list等)之间的区别是什么?
Also, In Dart doc it states that records are real values, what does that mean?
另外,在DART文档中,它指出记录是真实的价值,这是什么意思?
更多回答
优秀答案推荐
A record is not a "collection type". I think that is very misleading.
记录不是“集合类型”。我认为这非常具有误导性。
It is basically a very short and dynamic way to declare a class that holds fields and nothing else.
它基本上是一种非常简短和动态的方式来声明一个只包含字段的类。
For example ({int r, int g, int b}) color
this is a variable of a type that has three fields of type int, named r
, g
and b
.
例如({int r,int g,int b})COLOR这是一个类型的变量,它有三个int类型的字段,分别名为r、g和b。
You could have made a class:
你本可以上一堂课:
class Color {
final int r;
final int g;
final int b;
Color({this.r, this.b, this.g});
}
That would serve the same purpose, it's just a lot more work and a lot more class definitions. Because:
这将服务于相同的目的,只是有更多的工作和更多的类定义。因为:
Records automatically define hashCode
and ==
methods based on the structure of their fields.
So it is a very practical and time saving way to use field-aggregates. Or "data holder classes". It is not a replacement for collections. Collections are a varying number of elements of the same type, records are a predefined number of varying types.
因此,使用字段集合体是一种非常实用和节省时间的方式。或“数据持有者类”。它不是收藏的替代品。集合是相同类型的不同数量的元素,记录是预定义数量的不同类型。
/// this called record type
/// first you put your record's data types in brackets
/// the order is important
/// [myRecord] is the name of your record variable
/// (1,'kururu' , 28) remember the order (num ID , Object name , num age)
(num , Object , num) myRecord = (1 ,"Kururu" ,28);
void main(List<String> args) {
//using record to initialize multi variables in one line
//remember the order of your record (INT ,STRING ,INT)
// number ,name , age are your variable
// assign them to your record
// and that's it:)
var (number as int, name as String , age as int ) = myRecord;
print(number);
print(name) ;
print(age) ;
}
something like this?
像这样的吗?
更多回答
我是一名优秀的程序员,十分优秀!