Mega Code Archive

 
Categories / C# / Reflection
 

Set Non-Pubic Property

using System; using System.Reflection; namespace Homelidays.Web.SessionService.Tests {     /// <summary>     /// A helper class that eases reflection operations.     /// voici Les méthodes à implémenter au fur et à mesure des besoins:     ///     - internal static object CallNonPublicStaticMethod(string className, string methodName)     ///     - internal static object InstanciateNonPublicClass(string className)     /// </summary>     internal static class ReflectionUtility     {         /// <summary>         /// Call a non public property of an object.         /// </summary>         /// <param name="instance">Object whose method to call is private.</param>         /// <param name="propertyName">Name of the property to call.</param>         /// <param name="value">Value to pass to the porperty setter</param>         /// <returns>The object returned by the private method to call.</returns>         internal static object SetNonPubicProperty(object instance, string propertyName, object value)         {             Type type = instance.GetType();             var parameters = new object[1]; // alwasy 1 because a property setter could only have one parameter             var return_object = type.InvokeMember(                 propertyName,                 BindingFlags.Instance | BindingFlags.SetProperty,                 null,                 instance,                 parameters);             return return_object;         }     } }