fork download
  1. using System;
  2. using System.Reflection;
  3. using System.Linq;
  4.  
  5.  
  6. public static class TypeExtensions {
  7.  
  8. public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingAttr, Type[] types, Type returnType ) {
  9. var methods = type
  10. .GetMethods(BindingFlags.Static | BindingFlags.Public)
  11. .Where(mi => mi.Name == "op_Explicit")
  12. .Where(mi => mi.ReturnType == typeof(int));
  13.  
  14. if (!methods.Any())
  15. return null;
  16.  
  17. if (methods.Count() > 1)
  18. throw new System.Reflection.AmbiguousMatchException();
  19.  
  20.  
  21. return methods.First();
  22. }
  23.  
  24. public static MethodInfo GetImplicitCastToMethod(this Type type, Type returnType )
  25. {
  26. return type.GetMethod("op_Implicit", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, new Type[] { type }, returnType);
  27. }
  28.  
  29. public static MethodInfo GetExplicitCastToMethod(this Type type, Type returnType )
  30. {
  31. MethodInfo method = null;
  32.  
  33. method = type.GetMethod("op_Explicit", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, new Type[] { type }, returnType);
  34. if (method != null)
  35. return method;
  36.  
  37. method = returnType.GetMethod("op_Explicit", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, new Type[] { returnType }, type);
  38. return method;
  39. }
  40.  
  41.  
  42. }
  43.  
  44. public class Test
  45. {
  46.  
  47. public static void Main()
  48. {
  49.  
  50. MethodInfo m = typeof(IntPtr).GetImplicitCastToMethod(typeof(int));
  51. Console.WriteLine(m);
  52. object d = m.Invoke(null, new object[] { new IntPtr(0) });
  53. Console.WriteLine(d);
  54. }
  55. }
Success #stdin #stdout 0.04s 34048KB
stdin
Standard input is empty
stdout
Int32 op_Explicit(IntPtr)
0