コード例 #1
0
        /// <summary>
        /// Similar to <see cref="GetOrAddSharedExpression(Type, string, Func{Type, string, Expression}, Type)" />, except this is used when expression
        /// builders want to use local variables in block expressions to store the result of some operation in the expression tree built
        /// for a particular target.  Reusing one local variable is more efficient than declaring the same local multiple times.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="name">The name.</param>
        /// <param name="requestingType">Optional - the type of the object requesting this shared expression.  If this is provided,
        /// then the search for an existing shared expression will only work if the same requesting type was passed previously.</param>
        /// <exception cref="InvalidOperationException">Cannot add ParameterExpression: A shared expression of a different type has already been added with the same type and name.</exception>
        /// <remarks>When multiple expression trees from multiple targets are brought together into one lambda, there will
        /// often be many duplicate variables which could be shared.  So, if an <see cref="IExpressionBuilder" /> needs a local variable
        /// for a block, instead of simply declaring it directly through the <see cref="Expression.Parameter(Type, string)" /> function,
        /// it can use this function instead, which will return a previously created one if available.</remarks>
        public ParameterExpression GetOrAddSharedLocal(Type type, string name, Type requestingType = null)
        {
            // if no sharedExpressions dictionary, then we have a parent which will handle the call for us.
            if (this._sharedExpressions == null)
            {
                return(ParentContext.GetOrAddSharedLocal(type, name, requestingType));
            }

            try
            {
                return((ParameterExpression)GetOrAddSharedExpression(type, name, (t, s) => Expression.Parameter(t, s), requestingType));
            }
            catch (InvalidCastException)
            {
                throw new InvalidOperationException("Cannot add ParameterExpression: A shared expression of a different type has already been added with the same type and name.");
            }
        }