A closure is a function defined within a captured environment
Exemplo n.º 1
0
        /// <summary>
        /// Adds clsoure as an event handler for eventName on the target object
        /// </summary>
        /// <param name="target"></param>
        /// <param name="eventName"></param>
        /// <param name="closure"></param>
        /// <returns></returns>
        public static EventInfo AddEventHandler(object target, string eventName, Closure closure)
        {
            // Check for the requried event info.

            EventInfo theEvent = target.GetType().GetEvent(eventName, BindingFlags.IgnoreCase
                | BindingFlags.Instance
                | BindingFlags.Public
                | BindingFlags.NonPublic);

            if (theEvent == null)
            {
                throw new LSharpException(string.Format("No event {0} for {1}", eventName, target));
            }


            // Now, check to see if we need to construct a new class to handle this event binding.
            // If we already have an appropriate class just use that.

            Type bindingClass = null;


            if (EventHandlerMap.ContainsKey(theEvent.EventHandlerType) == false)
            {
                bindingClass = CreateNewBindingClass(theEvent);
                EventHandlerMap[theEvent.EventHandlerType] = bindingClass;
            }
            else
            {
                bindingClass = EventHandlerMap[theEvent.EventHandlerType];
            }


            // Now that we have the binding class worked out, create a new object and create a delegate
            // that's bound to that new object.

            Object bindingObject = Activator.CreateInstance(bindingClass,
                                                            new object[] { closure });

            Delegate newDelegate = Delegate.CreateDelegate(theEvent.EventHandlerType,
                                                           bindingObject,
                                                           bindingClass.GetMethod("EventHandler"));


            // Finally add the delegate to the event's list and return the found event info to the caller.

            theEvent.AddEventHandler(target, newDelegate);

            return theEvent;
        }
Exemplo n.º 2
0
        public static Macro MakeMacro(object parameters, object body, string documentation, Environment environment)
        {
            Closure closure = new Closure(parameters, body, environment);
            string signature = "";

            if (parameters != null)
                signature = PrintToString(parameters);

            return new Macro(new Func<object[], object>(closure.Invoke), signature, documentation, true);
        }