daily pastebin goal
60%
SHARE
TWEET

Untitled

a guest Aug 16th, 2018 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public static class ReflectionExtensions
  2. {
  3.     public static T GetFieldValue<T>(this object obj, string name)
  4.     {
  5.         var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
  6.         var field = obj.GetType().GetField(name, bindingFlags);
  7.         if (field == null)
  8.             field = obj.GetType().BaseType.GetField(name, bindingFlags);
  9.         return (T)field?.GetValue(obj);
  10.     }
  11.  
  12.     public static object InvokeMethod(this object obj, string methodName, params object[] methodParams)
  13.     {
  14.         var methodParamTypes = methodParams?.Select(p => p.GetType()).ToArray() ?? new Type[] { };
  15.         var bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
  16.         MethodInfo method = null;
  17.         var type = obj.GetType();
  18.         while (method == null && type != null)
  19.         {
  20.             method = type.GetMethod(methodName, bindingFlags, Type.DefaultBinder, methodParamTypes, null);
  21.             var intfs = type.GetInterfaces();
  22.             if (method != null)
  23.                 break;
  24.             foreach (var intf in intfs)
  25.             {
  26.                 method = intf.GetMethod(methodName, bindingFlags, Type.DefaultBinder, methodParamTypes, null);
  27.                 if (method != null)
  28.                     break;
  29.             }
  30.             type = type.BaseType;
  31.         }
  32.         return method?.Invoke(obj, methodParams);
  33.     }
  34. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top