// Try to find a match from a set of methods private void BindToMethod(ICollection <MethodInfo> methods, MemberElement previous, Type[] argTypes) { List <CustomMethodInfo> customInfos = new List <CustomMethodInfo>(); // Wrap the MethodInfos in our custom class foreach (MethodInfo mi in methods) { CustomMethodInfo cmi = new CustomMethodInfo(mi); customInfos.Add(cmi); } // Discard any methods that cannot qualify as overloads CustomMethodInfo[] arr = customInfos.ToArray(); customInfos.Clear(); foreach (CustomMethodInfo cmi in arr) { if (cmi.IsMatch(argTypes) == true) { customInfos.Add(cmi); } } if (customInfos.Count == 0) { // We have no methods that can qualify as overloads; throw exception this.ThrowFunctionNotFoundException(previous); } else { // At least one method matches our criteria; do our custom overload resolution this.ResolveOverloads(customInfos.ToArray(), previous, argTypes); } }
// Find the best match from a set of overloaded methods private void ResolveOverloads(CustomMethodInfo[] infos, MemberElement previous, Type[] argTypes) { // Compute a score for each candidate foreach (CustomMethodInfo cmi in infos) { cmi.ComputeScore(argTypes); } // Sort array from best to worst matches Array.Sort <CustomMethodInfo>(infos); // Discard any matches that aren't accessible infos = this.GetAccessibleInfos(infos); // No accessible methods left if (infos.Length == 0) { this.ThrowNoAccessibleMethodsException(previous); } // Handle case where we have more than one match with the same score this.DetectAmbiguousMatches(infos); // If we get here, then there is only one best match MyTargetMethodInfo = infos[0]; }
// Handle case where we have overloads with the same score private void DetectAmbiguousMatches(CustomMethodInfo[] infos) { List <CustomMethodInfo> sameScores = new List <CustomMethodInfo>(); CustomMethodInfo first = infos[0]; // Find all matches with the same score as the best match foreach (CustomMethodInfo cmi in infos) { if (((IEquatable <CustomMethodInfo>)cmi).Equals(first) == true) { sameScores.Add(cmi); } } // More than one accessible match with the same score exists if (sameScores.Count > 1) { this.ThrowAmbiguousMethodCallException(); } }