c# – 如何使用反射来获取泛型类型的扩展方法

前端之家收集整理的这篇文章主要介绍了c# – 如何使用反射来获取泛型类型的扩展方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
从互联网上的各种来源我收集了以下功能
  1. public static Nullable<T> TryParseNullable<T>(this Nullable<T> t,string input) where T : struct
  2. {
  3. if (string.IsNullOrEmpty(input))
  4. return default(T);
  5.  
  6. Nullable<T> result = new Nullable<T>();
  7. try
  8. {
  9. IConvertible convertibleString = (IConvertible)input;
  10. result = new Nullable<T>((T)convertibleString.ToType(typeof(T),CultureInfo.CurrentCulture));
  11. }
  12. catch (InvalidCastException) { }
  13. catch (FormatException) { }
  14.  
  15. return result;
  16. }

我已经把它变成了一个扩展方法,它的工作正常,如果我直接调用它:

  1. int? input = new int?().TryParseNullable("12345");

当我尝试使用来自另一个通用函数的上下文中的反射来调用它时,我的问题出现. SO充满了描述如何获取通用方法和静态方法的MethodInfo的答案,但我似乎无法以正确的方式将它们放在一起.
我已经正确地确定了传递的泛型类型本身是一个通用类型(Nullable<>),现在我想使用反射来调用Nullable上的TryParseNullable扩展方法

  1. public static T GetValue<T>(string name,T defaultValue)
  2. {
  3. string result = getSomeStringValue(name);
  4. if (string.IsNullOrEmpty(result)) return defaultValue;
  5.  
  6. try
  7. {
  8. if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>))
  9. {
  10. MethodInfo methodInfo;
  11.  
  12. //using the TryParse() of the underlying type works but isn't exactly the way i want to do it
  13. //-------------------------------------------------------------------------------------------
  14. NullableConverter nc = new NullableConverter(typeof(T));
  15. Type t = nc.UnderlyingType;
  16.  
  17. methodInfo = t.GetMethod("TryParse",BindingFlags.Public | BindingFlags.Static,Type.DefaultBinder,new[] { typeof(string),t.MakeByRefType() },null);
  18. if (methodInfo != null)
  19. {
  20. var inputParameters = new object[] { result,null };
  21. methodInfo.Invoke(null,inputParameters);
  22. return (T) inputParameters[1];
  23. }
  24.  
  25. //start of the problem area
  26. //-------------------------
  27.  
  28. Type ttype = typeof(T);
  29.  
  30. //this works but is undesirable (due to reference to class containing the static method):
  31. methodInfo = typeof(ParentExtensionsClass).GetMethod("TryParseNullable",BindingFlags.Public | BindingFlags.Static);
  32. if (methodInfo != null)
  33. Console.WriteLine(methodInfo);
  34.  
  35. //standard way of getting static method,doesn't work (GetMethod() returns null):
  36. methodInfo = ttype.GetMethod("TryParseNullable",BindingFlags.Public | BindingFlags.Static);
  37. if (methodInfo != null)
  38. Console.WriteLine(methodInfo);
  39.  
  40. //Jon Skeet's advised method,doesn't work in this case (again GetMethod() returns null):
  41. //(see footnote for link to this answer)
  42. methodInfo = ttype.GetMethod("TryParseNullable");
  43. methodInfo = methodInfo.MakeGenericMethod(ttype);
  44. if (methodInfo != null)
  45. Console.WriteLine(methodInfo);
  46.  
  47. //another random attempt (also doesn't work):
  48. methodInfo = ttype.GetMethod("TryParseNullable",new[] { typeof(string) },null);
  49. if (methodInfo != null)
  50. Console.WriteLine(methodInfo);
  51. }
  52.  
  53. // if we get this far,then we are not handling the type yet
  54. throw new ArgumentException("The type " + defaultValue.GetType() + " is not yet supported by GetValue<T>.","T");
  55. }
  56. catch (Exception e)
  57. {
  58. [snip]
  59. }
  60. }

有人可以让我摆脱我的苦难吗?
typeof(T)返回正确的类型信息,我想这可能是使用它有点不正确的GetMethod()调用,或者我没有指定正确的参数调用GetMethod().

Link to referenced Jon Skeet answer

解决方法

问题是扩展方法不会修改它们正在“扩展”的类型.幕后实际发生的情况是,编译器将所有似乎在对象上进行的调用透明地转换为调用静态方法.

即.

  1. int? input = new int?().TryParseNullable("12345");
  2. // becomes...
  3. int? input = YourClass.TryParseNullable(new int?(),"12345");

从那里,显而易见,为什么它不会通过反思出现.这也解释了为什么你必须为命名空间使用一个using指令,其中定义了用于编译器可见的扩展方法的YourClass.至于你如何实际获得这些信息,我不知道有没有办法,运行所有声明的类型(可能是有趣的类的过滤列表,如果你知道那种编译时的信息)看对于在它们上定义的ExtensionMethodAttribute([ExtensionMethod])的静态方法,然后尝试解析参数列表的MethodInfo,以解决它们是否在Nullable上工作.

猜你在找的C#相关文章