ReflectionService.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using System;
  2. using System.Reflection;
  3. namespace Muchinfo.WPF.Controls.WebBrowser
  4. {
  5. public static class ReflectionService
  6. {
  7. public readonly static BindingFlags BindingFlags =
  8. BindingFlags.Instance |
  9. BindingFlags.Public |
  10. BindingFlags.NonPublic |
  11. BindingFlags.FlattenHierarchy |
  12. BindingFlags.CreateInstance;
  13. public static object ReflectGetProperty(this object target, string propertyName)
  14. {
  15. if (target == null)
  16. throw new ArgumentNullException("target");
  17. if (string.IsNullOrWhiteSpace(propertyName))
  18. throw new ArgumentException("propertyName can not be null or whitespace", "propertyName");
  19. var propertyInfo = target.GetType().GetProperty(propertyName, BindingFlags);
  20. if (propertyInfo == null)
  21. throw new ArgumentException(string.Format("Can not find property '{0}' on '{1}'", propertyName, target.GetType()));
  22. return propertyInfo.GetValue(target, null);
  23. }
  24. public static object ReflectInvokeMethod(this object target, string methodName, Type[] argTypes, object[] parameters)
  25. {
  26. if (target == null)
  27. throw new ArgumentNullException("target");
  28. if (string.IsNullOrWhiteSpace(methodName))
  29. throw new ArgumentException("methodName can not be null or whitespace", "methodName");
  30. var methodInfo = target.GetType().GetMethod(methodName, BindingFlags, null, argTypes, null);
  31. if (methodInfo == null)
  32. throw new ArgumentException(string.Format("Can not find method '{0}' on '{1}'", methodName, target.GetType()));
  33. return methodInfo.Invoke(target, parameters);
  34. }
  35. }
  36. }