Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading;
- using System.Linq.Expressions;
- using System.Collections.Generic;
- public static class FastActivator{
- private static bool Initialized = false;
- private static bool _isCreatingCache = false;
- private static Dictionary<Type, Func<object>> Cache;
- public static void CreateCache()
- {
- if (Initialized)
- return;
- Cache = new Dictionary<Type, Func<object>>();
- _isCreatingCache = true;
- var thr = new Thread(()=>
- {
- foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
- {
- foreach(var t in asm.GetTypes())
- {
- if (t.GetConstructor(Type.EmptyTypes) != null && !t.ContainsGenericParameters)
- {
- Cache[t] = Expression.Lambda<Func<object>>(Expression.New(t)).Compile();
- }
- }
- }
- _isCreatingCache = false;
- Initialized = true;
- });
- thr.Start();
- }
- public static object CreateInstance(Type t)
- {
- if (!Initialized)
- {
- if (!_isCreatingCache)
- CreateCache();
- }
- if (!Cache.ContainsKey(t))
- {
- var shouldUnInit = (t.GetConstructor(Type.EmptyTypes) == null);
- if (shouldUnInit)
- {
- return System.Runtime.Serialization.FormatterServices.GetUninitializedObject(t);
- }
- else
- {
- return Activator.CreateInstance(t);
- }
- }
- return Cache[t]();
- }
- public static T CreateInstance<T>()
- {
- if (!Initialized)
- {
- if (!_isCreatingCache)
- CreateCache();
- }
- var t = typeof(T);
- if (!Cache.ContainsKey(t))
- {
- var shouldUnInit = (t.GetConstructor(Type.EmptyTypes) == null);
- if (shouldUnInit)
- {
- return (T)System.Runtime.Serialization.FormatterServices.GetUninitializedObject(t);
- }
- else
- {
- return Activator.CreateInstance<T>();
- }
- }
- return (T)Cache[t]();
- }
- public static Array CreateArray(Type type, int len)
- {
- return Activator.CreateInstance(type, new object[] { len }) as Array;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment