public MethodInfo Find(string methodName, Type targetType, object[] args) { var builder = new PredicateBuilder(); builder.MethodName = methodName; builder.MatchParameters = true; builder.MatchCovariantParameterTypes = true; // Find the method that has a compatible signature // and a matching method name var arguments = new List<object>(); if (args != null && args.Length > 0) arguments.AddRange(args); builder.RuntimeArguments.AddRange(arguments); builder.MatchRuntimeArguments = true; Predicate<MethodInfo> finderPredicate = builder.CreatePredicate(); var finder = new FuzzyFinder<MethodInfo>(); finder.Tolerance = .66; // Search for any previous matches MethodInfo bestMatch = finder.Find(finderPredicate, _cachedResults); if (bestMatch == null) { // If there isn't a match, search the current type // for an existing match IEnumerable<MethodInfo> methods = GetMethods(targetType); bestMatch = finder.Find(finderPredicate, methods); } return bestMatch; }
public void MethodMissing(object source, MethodMissingParameters missingParameters) { var builder = new PredicateBuilder(); // The current method name must match the given method name if (_methodName != missingParameters.MethodName) return; if (missingParameters.Arguments != null) builder.RuntimeArguments.AddRange(missingParameters.Arguments); builder.MatchRuntimeArguments = true; Predicate<MethodInfo> finderPredicate = builder.CreatePredicate(); var finder = new FuzzyFinder<MethodInfo>(); finder.Tolerance = .66; // Match the criteria against the target delegate var searchList = new List<MethodInfo>(new[] {_target.Method}); // Determine if the signature is compatible MethodInfo match = finder.Find(finderPredicate, searchList); if (match == null) return; // If the signature is compatible, then execute the method MethodInfo targetMethod = _target.Method; object result = null; try { result = targetMethod.Invoke(_target.Target, missingParameters.Arguments); missingParameters.Handled = true; } catch (TargetInvocationException ex) { missingParameters.Handled = false; throw ex.InnerException; } missingParameters.ReturnValue = result; }