有人可以解释一下 `List<BaseType>`
Can someone please explain `List<BaseType>`
在Dart cheatsheet to null-aware-operators 中说
Specifying types is handy when you initialize a list with contents of a subtype, but still want the list to be List<BaseType>
:
final aListOfBaseType = <BaseType>[SubType(), SubType()];
有人可以详细说明一下吗?
您可以在以下示例中看到这一点(输出来自 DartPad):
class BaseType {}
class SubType extends BaseType {}
void main() {
final aList = [SubType(), SubType()];
print(aList.runtimeType); // JSArray<SubType>
aList.add(BaseType()); // error: The constructor returns type 'BaseType' that isn't of expected type 'SubType'.
final aListOfBaseType = <BaseType>[SubType(), SubType()];
print(aListOfBaseType.runtimeType); // JSArray<BaseType>
aListOfBaseType.add(BaseType()); // works
}
因此,如果您没有为列表指定任何泛型类型,Dart 将尝试自动猜测类型。因此,如果列表仅使用 SubType
个对象进行初始化,则列表的类型将为 List<SubType>
.
由于列表定义为 List<SubType>
,您将无法向列表中添加任何 BaseType
对象。因此,如果您希望将列表定义为 List<BaseType>
,则需要在创建列表对象时进行定义。
在Dart cheatsheet to null-aware-operators 中说
Specifying types is handy when you initialize a list with contents of a subtype, but still want the list to be
List<BaseType>
:
final aListOfBaseType = <BaseType>[SubType(), SubType()];
有人可以详细说明一下吗?
您可以在以下示例中看到这一点(输出来自 DartPad):
class BaseType {}
class SubType extends BaseType {}
void main() {
final aList = [SubType(), SubType()];
print(aList.runtimeType); // JSArray<SubType>
aList.add(BaseType()); // error: The constructor returns type 'BaseType' that isn't of expected type 'SubType'.
final aListOfBaseType = <BaseType>[SubType(), SubType()];
print(aListOfBaseType.runtimeType); // JSArray<BaseType>
aListOfBaseType.add(BaseType()); // works
}
因此,如果您没有为列表指定任何泛型类型,Dart 将尝试自动猜测类型。因此,如果列表仅使用 SubType
个对象进行初始化,则列表的类型将为 List<SubType>
.
由于列表定义为 List<SubType>
,您将无法向列表中添加任何 BaseType
对象。因此,如果您希望将列表定义为 List<BaseType>
,则需要在创建列表对象时进行定义。