Exemplo n.º 1
0
        private static object TryCompile(ref ClosureInfo closureInfo,
                                         Type delegateType, Type[] paramTypes, Type returnType,
                                         Expression bodyExpr, IList <ParameterExpression> paramExprs)
        {
            if (!TryCollectBoundConstants(ref closureInfo, bodyExpr, paramExprs))
            {
                return(null);
            }

            if (closureInfo != null)
            {
                closureInfo.ConstructClosure();
            }

            var method = GetDynamicMethod(paramTypes, returnType, closureInfo);

            var il = method.GetILGenerator();

            if (!EmittingVisitor.TryEmit(bodyExpr, paramExprs, il, closureInfo))
            {
                return(null);
            }

            il.Emit(OpCodes.Ret); // emits return from generated method

            // create open delegate with closure object
            if (closureInfo == null)
            {
                return(method.CreateDelegate(delegateType));
            }

            return(method.CreateDelegate(delegateType, closureInfo.ClosureObject));
        }