Created
April 20, 2012 20:12
-
-
Save jeffwilcox/2431507 to your computer and use it in GitHub Desktop.
Reflection comparison
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Windows Phone / Standard .NET: | |
// var mi = dataLoaderType.GetMethod(methodName, paramTypes); | |
// Windows 8 XAML Metro style app: | |
var mi = dataLoaderType.GetTypeInfo().GetDeclaredMethods(methodName); | |
MethodInfo actualMethod = null; | |
foreach (var method in mi) | |
{ | |
// Eeeew code. | |
var parameters = method.GetParameters(); | |
if (parameters.Length == paramTypes.Length) | |
{ | |
bool success = true; | |
for (int i = 0; i < paramTypes.Length; i++) | |
{ | |
if (parameters[i].ParameterType != paramTypes[i]) | |
{ | |
success = false; | |
break; | |
} | |
} | |
if (success) | |
{ | |
actualMethod = method; | |
break; | |
} | |
} | |
} | |
if (actualMethod == null) | |
{ | |
throw new InvalidOperationException("Win8 can be a pain?"); | |
} | |
// An extension method... | |
// MethodInfo Type.GetMethod(String, Type[]) | |
// http://msdn.microsoft.com/en-us/library/6hy0h0z1.aspx | |
public static MethodInfo GetMethod(this Type type, string methodName, Type[] types) | |
{ | |
// Windows Phone / Standard .NET: | |
// var mi = dataLoaderType.GetMethod(methodName, paramTypes); | |
// Windows 8 XAML Metro style app: | |
// TODO: VALIDATE THIS WORKS! | |
var methods = type.GetTypeInfo().GetDeclaredMethods(methodName); | |
MethodInfo mi = null; | |
foreach (var method in methods) | |
{ | |
// Eeeew code. | |
var parameters = method.GetParameters(); | |
if (parameters.Length == types.Length) | |
{ | |
bool success = true; | |
for (int i = 0; i < types.Length; i++) | |
{ | |
if (parameters[i].ParameterType != types[i]) | |
{ | |
success = false; | |
break; | |
} | |
} | |
if (success) | |
{ | |
mi = method; | |
break; | |
} | |
} | |
} | |
if (mi == null) | |
{ | |
// throw new InvalidOperationException("The method could not be found."); | |
// Probably OK to return null ? Need to validate. | |
} | |
return mi; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You're saying 1 line -> 27 lines is unreasonable?