Gets a private field given by it's name on a specific object. - CSharp System.Reflection

CSharp examples for System.Reflection:FieldInfo

Description

Gets a private field given by it's name on a specific object.

Demo Code

// The MIT License (MIT)
using System.Reflection;
using System;//from w w  w .j a  v  a2  s .  com

public class Main{
        /// <summary>
        /// Gets a private field given by it's name on a specific object.
        /// </summary>
        /// <typeparam name="T">Defines what type the method should cast the field value to before return</typeparam>
        /// <param name="target">The target object on which to get the field from.</param>
        /// <param name="name">The name of the field to get.</param>
        /// <returns></returns>
        /// <example>
        /// public void AsExtentionMethod()
        /// {
        ///   MyClass myObjectOfMyClass = new MyClass();
        ///   string field = myObjectOfMyClass.GetPrivateField&lt;string&gt;("myField");
        /// }
        /// 
        /// public void AsStaticMethod()
        /// {
        ///   MyClass myObjectOfMyClass = new MyClass();
        ///   string field = PrivateMembersHelper.GetPrivateField&lt;string&gt;(myObjectOfMyClass, "myField");
        /// }
        /// </example>
        public static T GetPrivateField<T>(this object target, string name)
        {
            FieldInfo field = target.GetType().LocateField(name);
            return (T)field.GetValue(target);
        }
        private static FieldInfo LocateField(this Type targetType, string name)
        {
            try
            {
                FieldInfo fieldInfo = targetType.GetField(name, ALL_PRIVATE_FLAGS);
                if (fieldInfo == null && targetType.BaseType != typeof(object))
                    return targetType.BaseType.LocateField(name);
                return fieldInfo;
            }
            catch (ArgumentException)
            {
                if (targetType.BaseType != typeof(object))
                {
                    return targetType.BaseType.LocateField(name);
                }
                throw;
            }
        }
}

Related Tutorials