简体   繁体   English

Dart - 按类名调用类构造函数

[英]Dart - Call class constructor by class name

I have the following code:- 我有以下代码: -

  switch (code) {
    case "BleDisconnectedException":
      throw BleDisconnectedException(msg, details);
    case "BleGattException":
      throw BleGattException(msg, details);
    case "BleGattCallbackTimeoutException":
      throw BleGattCallbackTimeoutException(msg, details);
    case "BleCharacteristicNotFoundException":
      throw BleCharacteristicNotFoundException(msg, details);
    case "BleGattCannotStartException":
      throw BleGattCannotStartException(msg, details);
    default:
      throw e;
  }

How do I make dart automatically do the switch-case, ie call the class constructor by its name, provided as a String ? 如何使dart自动执行switch-case,即按名称调用类构造函数,以String提供?

As I know in current Dart is not possible, but you can do something like this: 正如我所知,目前的Dart是不可能的,但你可以这样做:

var factories = Map<String, Object Function()>{'Foo', () => new Foo(), 'Bar', () => new Bar()};

Object instance = factories['Foo']();

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

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