Creating Property Accessor Delegates

,

When the PropertyInfo instance has been obtained, it is used to create a delegate for the get and set accessors. For this the Delegate.CreateDelegate method is used, via a custom PropertyInfo extension method called CreateGetter, in the PropertyUtility class. Within the CreateGetter method, the type argument, required by the Delegate.CreateDelegate method, is generated using the Expression.GetFuncType method. If the property is of type string, for example, a type representing a Func<string> is produced. See the following excerpt:

public static Func<TProperty> CreateGetter<TProperty>(
    this PropertyInfo propertyInfo, object owner)
{
    ArgumentValidator.AssertNotNull(propertyInfo, "propertyInfo");
    ArgumentValidator.AssertNotNull(owner, "owner");

    Type getterType = Expression.GetFuncType(
                        new[] { propertyInfo.PropertyType });

    object getter = Delegate.CreateDelegate(
                        getterType, owner, propertyInfo.GetGetMethod());

    return (Func<TProperty>)getter;
}

The Expression.GetFuncType method is also equivalent to the Type method MakeGenericType, which could have been used instead, like so:

Type getterType = typeof(Func<>).MakeGenericType(propertyInfo.PropertyType);

Creating a delegate for the set accessor means resolving the generic Action type in the same manner:

public static Action<TProperty> CreateSetter<TProperty>(
    this PropertyInfo propertyInfo, object owner)
{
    ArgumentValidator.AssertNotNull(propertyInfo, "propertyInfo");
    ArgumentValidator.AssertNotNull(owner, "owner");

    var propertyType = propertyInfo.PropertyType;
    var setterType = Expression.GetActionType(new[] { propertyType });

    Delegate setter = Delegate.CreateDelegate(
                setterType, owner, propertyInfo.GetSetMethod());

    return (Action<TProperty>)setter;
}

These two methods provide the delegates that are retained by the ViewState class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.243.130