DART : 변수 식별자 이름을 특정 유형의 변수에만 문자열로 변환하는 방법

StackOverflow https://stackoverflow.com//questions/23025743

  •  21-12-2019
  •  | 
  •  

문제

여기에 다트를 사용합니다.

위의 제목이 제안되므로 3 개의 BOOL 인스턴스 변수가있는 클래스 (아래 참조)가 있습니다.내가하고 싶은 것은이 인스턴스 변수의 식별자 이름을 검사하고 각각의 문자열에서 각각을 인쇄하는 함수를 만듭니다.ClassMirror 클래스와 함께 제공되는 .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

도움이 되었습니까?

해결책

샘플 코드.

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
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top