为类(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]
尽管有点学究,但您没有得到Symbol,而是使用Symbol(
#iWantThisSymbol
)来获取成员,在这种情况下,这是一种方法。所以我将其重写为:import 'dart:mirrors';
class TestClass{
void iWantThisMethod(){}
void butNotThisOne(){}
}
void main(){
var justTheMethodIWant = reflectClass(TestClass).instanceMembers[#iWantThisMethod];
}
另外,有关
where()
的使用的一些注意事项:.where()
返回一个可迭代的,即使只有一个匹配的项。您可能需要firstWhere()
,它总是返回单个项目。 var justTheSymbolIWant = allSymbols.firstWhere((symbol) => symbol == #iWantThisSymbol);
关于reflection - Dart ,如何获取特定成员(member)的符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23665055/