Dart Set.from() 与 Set.of()

Md.*_*hed 5 constructor set dart

在 dart 中,Setclass 有两个不同的工厂构造函数Set.from()Set.of(). 它们返回的结果是相同的类型。它们之间有用例区别吗?如何决定使用哪一个?

请参阅此程序的输出:

void main() {
    List<int> myList = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5];

    Set<int> mySetFrom = Set.from(myList);
    Set<int> mySetOf = Set.of(myList);

    print("mySetFrom type: ${mySetFrom.runtimeType}");
    print("mySetFrom: ${mySetFrom}");

    print("mySetOf type: ${mySetOf.runtimeType}");
    print("mySetOf: ${mySetOf}");
}
Run Code Online (Sandbox Code Playgroud)

输出:

mySetFrom type: _CompactLinkedHashSet<int>
mySetFrom: {1, 2, 3, 4, 5}
mySetOf type: _CompactLinkedHashSet<int>
mySetOf: {1, 2, 3, 4, 5}
Run Code Online (Sandbox Code Playgroud)

Spa*_*atz 7

类型继承揭示的差异:

Set<Object> superSet = <Object>{'one', 'two', 'three'};
Run Code Online (Sandbox Code Playgroud)

Set.from()构造函数可用于从 superSet 进行向下转换

Set<String> subSet = Set<String>.from(superSet); // OK
Run Code Online (Sandbox Code Playgroud)

Set.of()不能

Set<String> anotherSubSet = Set<String>.of(superSet); // throws an error
// The argument type 'Set<Object>' can't be assigned to the parameter type 'Iterable<String>'.
Run Code Online (Sandbox Code Playgroud)

我认为Set.of()构造函数最好具有完全相同的类型,因为性能更好。