Locate Property - CSharp System.Reflection

CSharp examples for System.Reflection:PropertyInfo

Description

Locate Property

Demo Code

// The MIT License (MIT)
using System.Reflection;
using System;/* w  ww  .  j a v a2s.c o m*/

public class Main{
        #region Private Helpers.

        private static PropertyInfo LocateProperty(this Type targetType, string name, bool demandWrite, bool demandRead)
        {
            try
            {
                PropertyInfo propertyInfo = targetType.GetProperty(name, ALL_PRIVATE_FLAGS);

                if (targetType.BaseType != typeof(object))
                {
                    // ReSharper disable ConditionIsAlwaysTrueOrFalse
                    if ((demandRead && demandWrite) && (!propertyInfo.CanWrite || !propertyInfo.CanRead))
                        return targetType.BaseType.LocateProperty(name, demandWrite, demandRead);

                    if (demandWrite && !propertyInfo.CanWrite)
                        return targetType.BaseType.LocateProperty(name, demandWrite, demandRead);

                    if (demandRead && !propertyInfo.CanRead)
                        return targetType.BaseType.LocateProperty(name, demandWrite, demandRead);
                    // ReSharper restore ConditionIsAlwaysTrueOrFalse
                }

                return propertyInfo;
            }
            catch (ArgumentException)
            {
                if (targetType.BaseType != typeof(object))
                {
                    return targetType.BaseType.LocateProperty(name, demandWrite, demandRead);
                }
                throw;
            }
        }
        /// <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>
        /// <code>
        /// public void AsExtentionMethod()
        /// {
        ///   MyClass myObjectOfMyClass = new MyClass();
        ///   string field = myObjectOfMyClass.GetPrivateProperty&lt;string&gt;("myField");
        /// }
        /// 
        /// public void AsStaticMethod()
        /// {
        ///   MyClass myObjectOfMyClass = new MyClass();
        ///   string field = PrivateMembersHelper.GetPrivateProperty&lt;string&gt;(myObjectOfMyClass, "myField");
        /// }
        /// </code>
        /// </example>
        public static T GetProperty<T>(this object target, string name)
        {
            PropertyInfo property = target.GetType().LocateProperty(name, true, false);
            return (T)property.GetValue(target, null);
        }
}

Related Tutorials