Last active
August 1, 2018 20:04
-
-
Save deepumi/9ff477ba42323df69f886c369189040c to your computer and use it in GitHub Desktop.
Create instance using Reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class TypeActivator<T> | |
{ | |
private delegate T Activator<T>(params object[] args); | |
private static readonly Dictionary<string, Activator<T>> _items = new Dictionary<string, Activator<T>>(); | |
/// <summary> | |
/// | |
/// </summary> | |
/// <returns></returns> | |
public static T Create() | |
{ | |
lock (_items) | |
{ | |
var type = typeof(T); | |
if (_items.TryGetValue(type.Name, out var res)) return res(); | |
var lambda = Expression.Lambda(typeof(Activator<T>), Expression.New(type), Expression.Parameter(typeof(object[]), "args")); | |
var result = lambda.Compile() as Activator<T>; | |
_items.Add(type.Name, result); | |
return result(); | |
} | |
} | |
} | |
public static class ActivatorCreateInstance | |
{ | |
public static T Create<T>() | |
{ | |
return Activator.CreateInstance<T>(); | |
} | |
} | |
public static T CreateInstance<T>(Type objType) where T : class | |
{ | |
Func<T> returnFunc; | |
if (!ActivatorStore<T>.Store.TryGetValue(objType.FullName, out returnFunc)) | |
{ | |
var dynMethod = new DynamicMethod(objType.Name, objType, null, objType); | |
ILGenerator ilGen = dynMethod.GetILGenerator(); | |
ilGen.Emit(OpCodes.Newobj, objType.GetConstructor(Type.EmptyTypes)); | |
ilGen.Emit(OpCodes.Ret); | |
returnFunc = dynMethod.CreateDelegate(typeof(Func<T>)) as Func<T>; | |
ActivatorStore<T>.Store[objType.FullName]= returnFunc; | |
} | |
return returnFunc(); | |
} | |
internal static class ActivatorStore<T> | |
{ | |
internal static IDictionary<string, Func<T>> Store = new ConcurrentDictionary<string, Func<T>>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment