Call private method from abstract class

27/09/2012 17:38

Using System.Linq;
   public object InvokePrivate<T> (T instance, string methodName, params object[] obj)
        {
            var baseType = instance.GetType().BaseType;
            var types = GetTypes(obj);
            var method = baseType.GetMethod(methodName,
                System.Reflection.BindingFlags.Instance |
                System.Reflection.BindingFlags.NonPublic, null, types, null);

            return method.Invoke(instance, obj);

        }

        internal Type[] GetTypes(object[] obj)
        {
            IList<Type> list = new List<Type>();

            foreach (var item in obj)
            {
                list.Add(item.GetType());
            }

            return list.ToArray<Type>();

        }
//Call in test-ProjectNameWebPartBase is abstract class, "GetAllValidators" is private method

ProjectNameWebPartBase target = new MultipageFormWebPart();

List<Control> actual = (List<Control>)InvokePrivate<ProjectNameWebPartBase>(target, "GetAllValidators", controls);