mardi 3 janvier 2023

How to use Reflection in order to avoid value boxing?

I am exploring Blazor's QuickGrid source code and found one interesting spot here.

On the 45th line Steve Sanderson left a TODO with a potentially better alternative solution.

I could not resist my curiosity and decided to give it a try and benchmark the solution afterwards. But, unfortunately, my knowledge in Reflection is really poor.

Could anybody help me to understand how the ideas described in the Steve's comment could be achieved?

Thanks

UPD-1: Code snippet of what I have atm

    if( typeof(TProp).GetInterface(nameof(IFormattable)) != null ) {

    Type result = typeof(Func<,>).MakeGenericType(typeof(TGridItem), typeof(TProp));
        
    _cellTextFunc = item => FormatValue(compiledPropertyExpression);
}

    // TODO: Consider using reflection to avoid having to box every value just to call IFormattable.ToString
    // For example, define a method "string Format<U>(Func<TGridItem, U> property) where U: IFormattable", and
    // then construct the closed type here with U=TProp when we know TProp implements IFormattable

    private string FormatValue<U>( Func<TGridItem, U> property ) where U : IFormattable
    {
        return null;
    }




Aucun commentaire:

Enregistrer un commentaire