jeudi 6 août 2015

Using Runtime Generate Generic Type to Filter Using OfType<>

So dug around the Google and just can't seem to word this properly to find my answer to here I am.

this is what i currently have

Using these interfaces I will pass in a list of IConversionHelper

namespace InvestOne.Response.Mapper.Interfaces
{
    public interface IConversionHelper
    {
        bool CanHelp(object value, Type destinationType);
    }

    public interface IConversionHelper<out T> :IConversionHelper
    {
        T Convert(object value);
    }
}

Like So

    public Mapper(IEnumerable<IConversionHelper> conversionHelpers)
    {
        _conversionHelpers = conversionHelpers;
    }

Then when mapping will use these helpers like so

            var propType = prop.PropertyType;
            var value = @from[spectraCode.Code];
            var conversionType = typeof (IConversionHelper<>).MakeGenericType(propType);
            var conversionHelpers = _conversionHelpers.OfType<conversionType>();

the issue is in the last line and i understand the problem being that generics need to be at compile time and right now its not. so trying to find something similar to creating the generic type at run time only in this case filter out at run time.

Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire