System.Reflection.TypeFactory.GetFactory C# (CSharp) Method

GetFactory() public static method

Gets factory to create instance of type using the public parameterless ctor. Use it when you want to create many instances of the same type in different objects Aprox, 1.3x faster than Activator, almost as fast a manual if you cache and reuse the delegate
public static GetFactory ( Type t ) : Func
t Type
return Func
        public static Func<object> GetFactory(Type t)
        {
            Func<object> inv;      
            lock (actLock)
            {
                if (_actCache == null) _actCache = new Dictionary<Type, Func<object>>();
                if (!_actCache.TryGetValue(t,out inv))
                {
#if COREFX
                var constructor = t.GetConstructor(Type.EmptyTypes) ?? t.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).First();
#else
               var constructor = t.GetConstructor(Type.EmptyTypes)??t.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
#endif
                    var body = Expression.New(constructor);
                    inv = Expression.Lambda<Func<object>>(body).Compile();
                    _actCache[t] = inv;
                }

            }

            return inv;
        }
    }

Usage Example

Esempio n. 1
0
 /// <summary>
 /// Gets delegate to quickly create instances of type using public parameterless constructor.
 /// Use this only when you want to create LOTS of instances (dto scenario)
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public static Func <object> GetFactory(this Type type)
 {
     type.MustNotBeNull("type");
     return(TypeFactory.GetFactory(type));
 }