【问题标题】:Dart: How to convert variable identifier names to strings only for variables of a certain typeDart:如何仅为特定类型的变量将变量标识符名称转换为字符串
【发布时间】:2014-04-12 03:29:11
【问题描述】:

在这里使用 Dart。

正如上面的标题所暗示的,我有一个包含三个 bool 实例变量的类(如下所示)。我想要做的是创建一个函数来检查这些实例变量的标识符名称并将它们中的每一个打印在一个字符串中。 ClassMirror 类 ALMOST 附带的 .declarations getter 执行此操作,除了它还为我提供了构造函数的名称以及我在类中拥有的任何其他方法。这不好。所以我真正想要的是一种按类型过滤的方法(即,只给我布尔标识符作为字符串。)有什么方法可以做到这一点?

class BooleanHolder {

  bool isMarried = false;
  bool isBoard2 = false;
  bool isBoard3 = false; 

 List<bool> boolCollection; 

  BooleanHolder() {


  }

   void boolsToStrings() {

     ClassMirror cm = reflectClass(BooleanHolder);
     Map<Symbol, DeclarationMirror> map = cm.declarations;
     for (DeclarationMirror dm in map.values) {


      print(MirrorSystem.getName(dm.simpleName));

    }

  }

}

输出是: 已结婚 isBoard2 isBoard3 boolsToStrings BooleanHolder

【问题讨论】:

    标签: dart dart-mirrors


    【解决方案1】:

    示例代码。

    import "dart:mirrors";
    
    void main() {
      var type = reflectType(Foo);
      var found = filter(type, [reflectType(bool), reflectType(int)]);
      for(var element in found) {
        var name = MirrorSystem.getName(element.simpleName);
        print(name);
      }
    }
    
    List<VariableMirror> filter(TypeMirror owner, List<TypeMirror> types) {
      var result = new List<VariableMirror>();
      if (owner is ClassMirror) {
        for (var declaration in owner.declarations.values) {
          if (declaration is VariableMirror) {
            var declaredType = declaration.type;
            for (var type in types) {
              if (declaredType.isSubtypeOf(type)) {
                result.add(declaration);
              }
            }
          }
        }
      }
    
      return result;
    }
    
    class Foo {
      bool bool1 = true;
      bool bool2;
      int int1;
      int int2;
      String string1;
      String string2;
    }
    

    输出:

    bool1
    bool2
    int1
    int2
    

    【讨论】:

      猜你喜欢
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多