daily pastebin goal
46%
SHARE
TWEET

Untitled

a guest Mar 25th, 2019 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. static class Dynamic
  2. {
  3.     public static class GetEnumerator<TEnumerable, TEnumerator, TSource>
  4.         where TEnumerable : IEnumerable<TSource>
  5.         where TEnumerator : IEnumerator<TSource>
  6.     {
  7.         public static Func<TEnumerable, TEnumerator> Invoke { get; } = Create();
  8.  
  9.         static Func<TEnumerable, TEnumerator> Create()
  10.         {
  11.             var enumerableType = typeof(TEnumerable);
  12.             var getEnumerator = enumerableType.GetEnumeratorMethod<TSource>();
  13.             if (getEnumerator is null || !typeof(TEnumerator).IsAssignableFrom(getEnumerator.ReturnType))
  14.                 throw new Exception($"'{enumerableType.FullName}': type must be implicitly convertible to '{typeof(TEnumerable).FullName}'");
  15.  
  16.             var enumerable = Expression.Parameter(enumerableType, "enumerable");
  17.             var body = Expression.Call(enumerable, getEnumerator);
  18.             return Expression.Lambda<Func<TEnumerable, TEnumerator>>(body, enumerable).Compile();        
  19.         }
  20.     }
  21.  
  22.     static MethodInfo GetEnumeratorMethod<TSource>(this Type enumerableType)
  23.     {
  24.         const string MethodName = "GetEnumerator";
  25.  
  26.         var method = enumerableType.GetMethod(MethodName, BindingFlags.Public | BindingFlags.Instance);
  27.         if (!(method is null))
  28.             return method;
  29.  
  30.         var type = typeof(IEnumerable<>).MakeGenericType(typeof(TSource));
  31.         if (type.IsAssignableFrom(enumerableType))
  32.             return type.GetMethod(MethodName);
  33.  
  34.         type = typeof(IEnumerable);
  35.         if (type.IsAssignableFrom(enumerableType))
  36.             return type.GetMethod(MethodName);
  37.        
  38.         return null;
  39.     }
  40. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top