要使用字符串,您必须使用反射来获取委托;
string searchRulesMethodName = "SearchRules1"; Predicatepredicate = (Predicate ) Delegate.CreateDelegate(typeof(Predicate ), typeof(Program).GetMethod(searchRulesMethodName)); var results = GetSearchResults(predicate);
当然,switch
如果你在编译时知道所有选项,那么会更快更安全!
Predicatepredicate; switch (searchRulesMethodName) { case "SearchRules1": predicate = SearchRules1; break; case "SearchRules2": predicate = SearchRules2; break; default: throw new InvalidOperationException("Unknown filter: " + searchRulesMethodName); } var results = GetSearchResults(predicate);