[英]Dart - Call class constructor by class name
我有以下代碼: -
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;
}
如何使dart自動執行switch-case,即按名稱調用類構造函數,以String
提供?
正如我所知,目前的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.