Evolution/Evolution/Activator.cs
/// <summary>
/// Gets a delegate to instantiate an object from a given constructor
/// </summary>
/// <param name="ctor">Constructor of the object to return</param>
/// <returns></returns>
Gets a delegate to instantiate an object from a given constructor
Gets a delegate to instantiate an object from a given constructor
public static ObjectActivator GetActivator
            (ConstructorInfo ctor)
        {
            ParameterInfo[] paramsInfo = ctor.GetParameters();
            ParameterExpression param =
                Expression.Parameter(typeof (object[]), "args");
            Expression[] argsExp =
                new Expression[paramsInfo.Length];
            for (int i = 0; i < paramsInfo.Length; i++)
            {
                Expression index = Expression.Constant(i);
                Type paramType = paramsInfo[i].ParameterType;
                Expression paramAccessorExp =
                    Expression.ArrayIndex(param, index);
                Expression paramCastExp =
                    Expression.Convert(paramAccessorExp, paramType);
                argsExp[i] = paramCastExp;
            }
            NewExpression newExp = Expression.New(ctor, argsExp);
            LambdaExpression lambda =
                Expression.Lambda(typeof (ObjectActivator), newExp, param);
            ObjectActivator compiled = (ObjectActivator) lambda.Compile();
            return compiled;
        }
public static ObjectActivator GetActivator ( ConstructorInfo ctor ) { ParameterInfo [ ] paramsInfo = ctor . GetParameters ( ) ; ParameterExpression param = Expression . Parameter ( typeof ( object [ ] ) , " " ) ; Expression [ ] argsExp = new Expression [ paramsInfo . Length ] ; for ( int i = 0 ; i < paramsInfo . Length ; i ++ ) { Expression index = Expression . Constant ( i ) ; Type paramType = paramsInfo [ i ] . ParameterType ; Expression paramAccessorExp = Expression . ArrayIndex ( param , index ) ; Expression paramCastExp = Expression . Convert ( paramAccessorExp , paramType ) ; argsExp [ i ] = paramCastExp ; } NewExpression newExp = Expression . New ( ctor , argsExp ) ; LambdaExpression lambda = Expression . Lambda ( typeof ( ObjectActivator ) , newExp , param ) ; ObjectActivator compiled = ( ObjectActivator ) lambda . Compile ( ) ; return compiled ; }
Gets a delegate to instantiate an object from a given constructor
Gets a delegate to instantiate an object from a given constructor
//create a single param of type object[] //pick each arg from the params array  //and create a typed expression of them //make a NewExpression that calls the //ctor with the args we just created //create a lambda with the New //Expression as body and our param object[] as arg //compile it
None
ctor
ConstructorInfo
Constructor of the object to return
Constructor of the object to return