Skip to content

Instantly share code, notes, and snippets.

@coenm
Last active August 29, 2015 14:13
Show Gist options
  • Save coenm/3ad7309549637dc4f2c4 to your computer and use it in GitHub Desktop.
Save coenm/3ad7309549637dc4f2c4 to your computer and use it in GitHub Desktop.
Helper methods to execute non public Methods or get/set non public properties.
using System;
using System.Reflection;
namespace com.github.coenm
{
public static class NonPublicMethodsHelper
{
public static MethodInfo GetNonPublicMethod(object instance, string methodName)
{
var instanceType = instance.GetType();
return GetNonPublicMethod(instanceType, methodName);
}
public static MethodInfo GetNonPublicMethod(Type instanceType, string methodName)
{
return instanceType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
}
public static PropertyInfo GetNonPublicProperty(Type instanceType, string propertyName)
{
return instanceType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
}
public static void InvokeNonPublicMethod(object instance, string methodName, object[] parameters = null)
{
var method = GetNonPublicMethod(instance, methodName);
method.Invoke(instance, parameters);
}
public static T InvokeNonPublicMethod<T>(object instance, string methodName, object[] parameters = null)
{
var method = GetNonPublicMethod(instance, methodName);
var result = (T)method.Invoke(instance, parameters);
return result;
}
public static T GetValueOfNonPublicProperty<T>(object instance, string propertyname)
{
var instanceType = instance.GetType();
var prop = GetNonPublicProperty(instanceType, propertyname);
var value = (T)prop.GetValue(instance);
return value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment