using System; using System.Collections.Generic; using System.Reflection; namespace MbUnit.ReSharperRunner.MbUnit { public class ReflectionUtility { public static MethodInfo FindMethod(string assembly, string methodName) { Type type = Type.GetType(string.Format("{0}, {1}", GetTypeName(methodName), assembly), true); return FindMethod(type, GetMethodSignature(methodName)); } public static MethodInfo FindMethod(string methodName) { Type type = Type.GetType(GetTypeName(methodName), true); return FindMethod(type, GetMethodSignature(methodName)); } public static string GetTypeName(string methodName) { int bracketPosition = methodName.IndexOf('('); int dotPosition = methodName.LastIndexOf('.', bracketPosition > 0 ? bracketPosition : methodName.Length); return methodName.Substring(0, dotPosition); } public static MethodInfo FindMethod(Type type, string methodSignature) { return type.GetMethod(GetMethodName(methodSignature), GetParameterTypes(methodSignature)); } private static Type[] GetParameterTypes(string methodSignature) { List resultTypes = new List(); foreach (string typeName in GetParameterList(methodSignature)) { if (typeName.IndexOf(' ') > 0) // Wenn noch eine Variablenname dran hängt { resultTypes.Add(Type.GetType(typeName.Substring(0, typeName.IndexOf(' ')), true)); } else { resultTypes.Add(Type.GetType(typeName, true)); } } return resultTypes.ToArray(); } private static string[] GetParameterList(string methodSignature) { List parameterList = new List(); int firstBracket = methodSignature.IndexOf('('); if (firstBracket > 0) { int lastBracket = methodSignature.LastIndexOf(')'); if (lastBracket > 0) { string textParameters = methodSignature.Substring(firstBracket + 1, lastBracket - firstBracket - 1); string[] parameters = textParameters.Split(','); for (int i = 0; i < parameters.Length; i++) { parameterList.Add(parameters[i].Trim()); } } } return parameterList.ToArray(); } private static string GetMethodName(string methodSignature) { int bracketPos = methodSignature.IndexOf('('); int lastDotPos = bracketPos > 0 ? methodSignature.LastIndexOf('.', bracketPos) : methodSignature.LastIndexOf('.'); lastDotPos++; int methodLength = bracketPos > 0 ? bracketPos - lastDotPos : methodSignature.Length - lastDotPos; return methodSignature.Substring(lastDotPos, methodLength); } private static string GetMethodSignature(string fullMethodName) { int bracketPos = fullMethodName.IndexOf('('); int lastDotPos = bracketPos > 0 ? fullMethodName.LastIndexOf('.', bracketPos) : fullMethodName.LastIndexOf('.'); return lastDotPos >= 0 ? fullMethodName.Substring(lastDotPos + 1) : fullMethodName; } } }