Created
January 12, 2020 13:15
-
-
Save jasmin-mistry/4f1e8bd3771b7c171175c2d4e13ea53e to your computer and use it in GitHub Desktop.
Create Instance for a generic type with arguments for constructor
This file contains hidden or 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 ActivatorExt | |
{ | |
private static ObjectActivator<T> GetActivator<T>(ConstructorInfo ctor) | |
{ | |
var paramsInfo = ctor.GetParameters(); | |
var param = Expression.Parameter(typeof(object[]), "args"); | |
var argsExp = new Expression[paramsInfo.Length]; | |
for (var i = 0; i < paramsInfo.Length; i++) | |
{ | |
Expression index = Expression.Constant(i); | |
var paramType = paramsInfo[i].ParameterType; | |
Expression paramAccessorExp = Expression.ArrayIndex(param, index); | |
Expression paramCastExp = Expression.Convert(paramAccessorExp, paramType); | |
argsExp[i] = paramCastExp; | |
} | |
var newExp = Expression.New(ctor, argsExp); | |
var lambda = Expression.Lambda(typeof(ObjectActivator<T>), newExp, param); | |
var compiled = (ObjectActivator<T>) lambda.Compile(); | |
return compiled; | |
} | |
public static T CreateInstance<T>(params object[] args) | |
{ | |
var ctor = typeof(T).GetConstructors().First(); | |
var createdActivator = GetActivator<T>(ctor); | |
return createdActivator(args); | |
} | |
private delegate T ObjectActivator<out T>(params object[] args); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment