|
| 1 | +namespace Schema.NET |
| 2 | +{ |
| 3 | + using System; |
| 4 | + using System.Collections.Concurrent; |
| 5 | + using System.Collections.Generic; |
| 6 | + using System.Linq.Expressions; |
| 7 | + using System.Reflection; |
| 8 | + using System.Text; |
| 9 | + |
| 10 | + /// <summary> |
| 11 | + /// A faster version of <see cref="Activator.CreateInstance(System.Type, object[])"/> by providing constructor delegates. |
| 12 | + /// </summary> |
| 13 | + internal static class FastActivator |
| 14 | + { |
| 15 | + private static readonly ConcurrentDictionary<(Type, Type), Delegate> ConstructorDelegateLookup = new ConcurrentDictionary<(Type, Type), Delegate>(); |
| 16 | + |
| 17 | + /// <summary> |
| 18 | + /// Creates a constructor delegate for the specified type. |
| 19 | + /// </summary> |
| 20 | + /// <typeparam name="T1">Type of first argument for constructor.</typeparam> |
| 21 | + /// <param name="objectType">The object to find the constructor.</param> |
| 22 | + /// <returns>The constructor delegate.</returns> |
| 23 | + public static Func<T1, object> GetDynamicConstructor<T1>(Type objectType) |
| 24 | + { |
| 25 | + var constructorKey = (objectType, typeof(T1)); |
| 26 | + if (!ConstructorDelegateLookup.TryGetValue(constructorKey, out var constructorDelegate)) |
| 27 | + { |
| 28 | + var constructor = GetConstructorInfo(objectType, typeof(T1)); |
| 29 | + constructorDelegate = CreateConstructorDelegate<T1>(constructor); |
| 30 | + ConstructorDelegateLookup.TryAdd(constructorKey, constructorDelegate); |
| 31 | + } |
| 32 | + |
| 33 | + return constructorDelegate as Func<T1, object>; |
| 34 | + } |
| 35 | + |
| 36 | + private static Func<T1, object> CreateConstructorDelegate<T1>(ConstructorInfo constructor) => Expression.Lambda<Func<T1, object>>( |
| 37 | + Expression.Convert( |
| 38 | + Expression.New(constructor, ConstructorParameter<T1>.SingleParameter), |
| 39 | + typeof(object)), |
| 40 | + ConstructorParameter<T1>.SingleParameter).Compile(); |
| 41 | + |
| 42 | + private static ConstructorInfo GetConstructorInfo(Type objectType, Type parameter1) |
| 43 | + { |
| 44 | + foreach (var constructor in objectType.GetTypeInfo().DeclaredConstructors) |
| 45 | + { |
| 46 | + var parameters = constructor.GetParameters(); |
| 47 | + if (constructor.IsPublic && parameters.Length == 1 && parameters[0].ParameterType == parameter1) |
| 48 | + { |
| 49 | + return constructor; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return null; |
| 54 | + } |
| 55 | + |
| 56 | + private static class ConstructorParameter<T1> |
| 57 | + { |
| 58 | + public static readonly ParameterExpression[] SingleParameter = new[] { Expression.Parameter(typeof(T1)) }; |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments