简体   繁体   English

我们如何从 dart 中的抽象类实例化?

[英]how we can instantiate from abstract class in dart?

How we can instantiate from abstract class in dart like below:我们如何从 dart 中的抽象类实例化,如下所示:

int a = 5;
String a = ‘Hello’;
List<int> myList1= [50,60,70];

these classes are all abstract but we get instance from each one.这些类都是抽象的,但我们从每个类中获取实例。

Abstract classes is allowed to have factory constructors and/or static methods which returns instances which are compatible with the abstract class.允许抽象类具有工厂构造函数和/或静态方法,这些方法返回与抽象类兼容的实例。

So we can do things like this where the actual implementation is hidden from users of our library:所以我们可以做这样的事情,其中​​实际实现对我们库的用户是隐藏的:

abstract class A {
  String getString();

  factory A() => _A();
  static A getA() => _A();
}

class _A implements A {
  @override
  String getString() => 'Hello World';
}

void main() {
  A a1 = A();
  A a2 = A.getA();
  print(a1.getString()); // Hello World
  print(a2.getString()); // Hello World
  print(a1.runtimeType); // _A
  print(a2.runtimeType); // _A
}

The expressions 5 , 'hello' and [50, 60, 70] are literals , not class instantiations (no constructor is invoked in the creation, well, as far as you know).表达式5 , 'hello'[50, 60, 70]文字,而不是类实例化(就您所知,在创建过程中没有调用构造函数)。 The literals produce values which satisfy the interfaces int , String and List<int> , in some magical way which the language doesn't specify (it just says what the end result must be), and the objects do not have to be actual instances of those types.文字产生满足接口intStringList<int> ,以某种语言没有指定的神奇方式(它只是说明最终结果必须是什么),并且对象不必是实际实例那些类型。

In practice, they aren't.在实践中,他们不是。 Each platform has their own implementation.每个平台都有自己的实现。 On the native VM, 5 is an instance of _Smi (short for "small integer"), 'hello' is an instance of _OneByteString and [50, 60, 70] is an instance of _GrowableList<String> .在原生 VM 上, 5_Smi的实例(“小整数”的缩写), 'hello'_OneByteString的实例, [50, 60, 70]_GrowableList<String>的实例。 All these implementations classes are hidden from users because they are platform-specific.所有这些实现类都对用户隐藏,因为它们是特定于平台的。 On the web, each class uses an underlying JavaScript type, Number , String and Array , because those are very efficient, and then lies about it if asked, pretending that they are really Dart classes.在网络上,每个类都使用底层 JavaScript 类型NumberStringArray ,因为它们非常有效,然后如果被问到就撒谎,假装它们真的是 Dart 类。

You cannot create an instance of an abstract class.不能创建抽象类的实例。 You can create an instance of a class which implements the interface of an abstract class.可以创建一个实现抽象类接口的类的实例。 That's what's happening here — plus some platform-native magic to hide which class that is, because you shouldn't care about the native implementations below.这就是这里发生的事情——加上一些平台原生的魔法来隐藏那个类,因为你不应该关心下面的原生实现。 (Also because that might just change in the next Dart SDK release, because some other implementation is more efficient.) (也因为这可能会在下一个 Dart SDK 版本中改变,因为其他一些实现更有效。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM