【问题标题】:How to loop through list of classes and assign them to a variable如何遍历类列表并将它们分配给变量
【发布时间】:2023-03-19 19:35:01
【问题描述】:

如何遍历类列表并根据条件将它们分配给变量。 示例:


class A {
  static List items = ['item1', 'item2', 'item3'];
}

class B {
  static List items = ['item1', 'item2', 'item3'];
}

class C {
  static List items = ['item1', 'item2', 'item3'];
}


class SelectSuitableClass {
  var selectedClass;
  String item;
  List myClasses = [A, B, C];

  SelectSuitableClass(this.item) {

    outerFor: for (var cl in myClasses){

       for (var i in cl.items) {
         if (item.contains(i)) {

           selectedClass = cl();
           break outerFor;

         }
       }

       if(selectedClass == null) {
         throw 'some error';
       }
    }   
  }
}

在python中这个代码是可能的。

我们如何在 dart 中实现这一点。

【问题讨论】:

    标签: dart


    【解决方案1】:

    如果不使用在大多数平台上不可用的反射 (dart:mirrors),您将无法在 Dart 中实现此目的。

    类列表包含Type 对象、[A, B, C]Type 对象仅适用于两件事:比较相等和在使用镜像库时用作标记。

    您不能通过代表该类的Type 对象访问该类的静态成员,您必须以编译器可以静态查看您正在访问的成员的方式访问该静态成员.

    为了在结果取决于接收者的地方进行查找,您需要有一个实例成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 2021-01-22
      • 1970-01-01
      • 1970-01-01
      • 2022-11-20
      相关资源
      最近更新 更多