src/Mimp.SeeSharper.Reflection/PropertyInfoExtensions.cs
/// <summary>
/// Return a compiled delegate to access the property.
/// </summary>
/// <param name="property"></param>
/// <param name="delegateType"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException">If the delegate hasn't one parameter for the instance.</exception>
/// <exception cref="InvalidOperationException">If the property type isn't castable to the delegate return type.</exception>
Return a compiled delegate to access the property.
Return a compiled delegate to access the property .
public static Delegate GetInstanceAccessDelegate(this PropertyInfo property, Type delegateType)
        {
            if (property is null)
                throw new ArgumentNullException(nameof(property));
            if (delegateType is null)
                throw new ArgumentNullException(nameof(delegateType));
            var parameterTypes = delegateType.GetDelegateParameterTypes().ToArray();
            if (parameterTypes.Length != 1)
                throw new ArgumentException($@"Delegate ""{delegateType}"" has an incorrect number of parameters", nameof(delegateType));
            var instance = Expression.Parameter(parameterTypes[0], "instance");
            return Expression.Lambda(delegateType,
                Expression.Convert(
                    Expression.MakeMemberAccess(
                        Expression.Convert(instance, property.ReflectedType!),
                        property
                    ),
                    delegateType.GetDelegateReturnType()
                ),
                instance
            ).Compile();
        }
public static Delegate GetInstanceAccessDelegate ( this PropertyInfo property , Type delegateType ) { if ( property is null ) throw new ArgumentNullException ( nameof ( property ) ) ; if ( delegateType is null ) throw new ArgumentNullException ( nameof ( delegateType ) ) ; var parameterTypes = delegateType . GetDelegateParameterTypes ( ) . ToArray ( ) ; if ( parameterTypes . Length != 1 ) throw new ArgumentException ( $@" Delegate  "" { delegateType } ""  has an incorrect number of parameters " , nameof ( delegateType ) ) ; var instance = Expression . Parameter ( parameterTypes [ 0 ] , " " ) ; return Expression . Lambda ( delegateType , Expression . Convert ( Expression . MakeMemberAccess ( Expression . Convert ( instance , property . ReflectedType ! ) , property ) , delegateType . GetDelegateReturnType ( ) ) , instance ) . Compile ( ) ; }
Return a compiled delegate to access the property.
Return a compiled delegate to access the property .
None
None
If the delegate hasn't one parameter for the instance.
If the delegate hasn ' t one parameter for the instance .
If the property type isn't castable to the delegate return type.
If the property type isn ' t castable to the delegate return type .
PropertyInfo
this
delegateType
Type
None
property
None