Mega Code Archive

 
Categories / C# / Reflection
 

Set Non-Pubic Field

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>         /// Set the value of a non public field.         /// </summary>         /// <param name="instance">Object whose fild should be set.</param>         /// <param name="fieldName">Name of the field to set.</param>         /// <param name="value">Value to set the field with.</param>         internal static void SetNonPublicField(object instance, string fieldName, object value)         {             Type type = instance.GetType();             var parameters = new object[1]; // alwasy 1 because a property setter could only have one parameter             parameters[0] = value;             type.InvokeMember(                 fieldName,                 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetField,                 null,                 instance,                 parameters);         }     } }