mercredi 9 octobre 2019

Convert from TResult to IEnumerable

I'm implementing a Linq provider. There is a generic method T IQueryProvider.Execute<T>(Expression expresion). In my implementation I want to delegate it to another method IEnumerable<T> ExecuteImpl<T>(Expression expression) if TResult is an IEnumerable<T>. Is it possible to do without reflection?

Currently I have code similar to following;

public class MyQueryProvider : IQueryProvider
{
    readonly MethodInfo EnumerableExecuteMethod = typeof(MyQueryProvider).GetMethod(nameof(ExecuteImpl));

    public TResult Execute<TResult>(Expression expression)
    {
        if (typeof(IEnumerable).IsAssignableFrom(typeof(TResult)))
        {
            return (TResult) EnumerableExecuteMethod
                .MakeGenericMethod(typeof(TResult).GetGenericArguments()[0])
                .Invoke(this, new object[] {expression});
        }

        throw new NotImplementedException();
    }

    public IEnumerable<T> ExecuteImpl<T>(Expression expression) => throw new NotImplementedException();
}




Aucun commentaire:

Enregistrer un commentaire