This project is read-only.

Small adjustment to include non-public properties

Jul 31, 2013 at 2:16 PM
Edited Jul 31, 2013 at 2:17 PM
Hello,

I like this small but useful project.

I'm using the FastProperty to hijack some private or protected properties. However, I have to make a minor change.

Especially, in the "MakeDelegates" method, I changed this code :
            if (this.Property.CanRead)
            {
                getExpression = Expression.Call(instanceExpression, this.Property.GetGetMethod());
            }
to :
            if (this.Property.CanRead)
            {
                getExpression = Expression.Call(instanceExpression, this.Property.GetGetMethod(true));
            }
And also:
            if (this.Property.CanWrite)
            {
                // create the call to the set method
                setExpression = Expression.Call(instanceExpression, this.Property.GetSetMethod(), valueExpression);
                this.Set = Expression.Lambda<Action<T, P>>(setExpression, instance, value).Compile();
            }
to
            if (this.Property.CanWrite)
            {
                // create the call to the set method
                setExpression = Expression.Call(instanceExpression, this.Property.GetSetMethod(true), valueExpression);
                this.Set = Expression.Lambda<Action<T, P>>(setExpression, instance, value).Compile();
            }
I specify true on both methods (GetGetMethod and GetSetMethod) to also include non public methods. With this modification, public and non-public methods will be retrieved.

This allowed me to handle some scenario like :
        private static readonly IFastProperty<Control, StateBag> g_ViewStateProperty = FastProperty<Control, StateBag>.Make(
            typeof(Control)
            .GetProperty("ViewState", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
            );

        public static bool ExecuteOnce(Control owner, Action code)
        {
            if (owner == null) throw new ArgumentNullException("owner");
            if (code == null) throw new ArgumentNullException("code");

            var viewstate = g_ViewStateProperty.Get(owner);

            if (viewstate["ExecutedOnce"] == null)
            {
                code();
                viewstate["ExecutedOnce"] = true;
                return true;
            }
            else
            {
                return false;
            }
        }
I'm ok with my local change, but you may will to update your code like I did?

(I won't submit a patch, as codeplex is too complex to fork projects... but it's another debate)


Hope that helps