سؤال

What is the most efficient way of getting the symbol for a single member of a class?

import 'dart:mirrors';

class TestClass{
    void iWantThisSymbol(){}
    void butNotThisOne(){}
}

/**
 * I can get all the symbols and filter down but this isn't nice
 */
void main(){
    var allSymbols = reflectClass(TestClass).instanceMembers.keys;
    var justTheSymbolIWant = allSymbols.where((symbol) => symbol.toString().contains('iWantThisSymbol')); // this doesnt seem very efficient or maintainable
}
هل كانت مفيدة؟

المحلول

var justTheSymbolIWant = reflectClass(TestClass).instanceMembers[#iWantThisSymbol]

Although, to be a bit pedantic, you're not get getting a Symbol, you're using a Symbol (#iWantThisSymbol) to get a member, which in this case is a method. So I would rewrite this as:

import 'dart:mirrors';

class TestClass{
    void iWantThisMethod(){}
    void butNotThisOne(){}
}

void main(){
    var justTheMethodIWant = reflectClass(TestClass).instanceMembers[#iWantThisMethod];
}

Also, a few things about that use of where():

  1. If you do want to filter a list of Symbols, you don't need to them convert to a String, you can just compare symbol instances directly.
  2. .where() returns an iterable, even if there's only one item that matches. You probably want firstWhere() which always returns a single item.
var justTheSymbolIWant = allSymbols.firstWhere((symbol) => symbol == #iWantThisSymbol);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top