public static AsyncInvocationRegion Create(Delegate @delegate)
        {
#if PORTABLE
            return Create(@delegate.GetMethodInfo());
#else
            return Create(@delegate.Method);
#endif
        }
        public static bool IsAsyncOperation(Delegate @delegate)
        {
#if PORTABLE
            return IsAsyncOperation(@delegate.GetMethodInfo());
#else
            return IsAsyncOperation(@delegate.Method);
#endif
        }
        void IActionInvoker.ClearIfMatched(Delegate action, object recipient) {
            object target = Target;
            if(recipient != target)
                return;
#if !NETFX_CORE
            if(action != null && action.Method.Name != MethodName)
#else
            if(action != null && action.GetMethodInfo().Name != MethodName)
#endif
                return;
            targetReference = null;
            ClearCore();
        }
Exemple #4
0
        /// <summary>
        /// Returns a value indicating whether the current weak delegate is a match (equivalent) for the specified strong delegate.
        /// </summary>
        /// <param name="strongDelegate">The <see cref="Delegate">delegate</see> to evaluate.</param>
        /// <returns>True if the current weak delegate is a match for the specified strong delegate; otherwise, false.</returns>
        public virtual bool IsMatch( Delegate strongDelegate )
        {
            if ( strongDelegate == null )
                return false;

            if ( !object.Equals( strongDelegate.Target, Target ) )
                return false;

            if ( !strongDelegate.GetMethodInfo().Equals( method ) )
                return false;

            return true;
        }
 public ScriptUserdataDelegate(Script script, Delegate value) : base(script) {
     this.m_Delegate = value;
     this.m_Value = value;
     this.m_ValueType = value.GetType();
     var method = m_Delegate.GetMethodInfo();
     var infos = method.GetParameters();
     var dynamicDelegate = method.Name.Equals(Script.DynamicDelegateName);
     int length = dynamicDelegate ? infos.Length - 1 : infos.Length;
     m_Objects = new object[length];
     for (int i = 0; i < length; ++i) {
         var p = infos[dynamicDelegate ? i + 1 : i];
         m_Parameters.Add(new FunctionParameter(p.ParameterType, p.DefaultValue));
     }
 }
Exemple #6
0
            public bool IsEqualTo(object source, EventInfo eventInfo, Delegate handler)
            {
                if (source == this.source && eventInfo == this.eventInfo)
                {
                    object target;

                    if (handlerTarget.TryGetTarget(out target))
                    {
                        return(handler.Target == target && handler.GetMethodInfo() == handlerMethod);
                    }
                }

                return(false);
            }
        public void RegisterFunction(string functionName, Delegate function, bool isOverWritable)
        {
            if (string.IsNullOrEmpty(functionName))
                throw new ArgumentNullException("functionName");

            if (function == null)
                throw new ArgumentNullException("function");

            Type funcType = function.GetType();

            if (!funcType.FullName.StartsWith("System.Func"))
                throw new ArgumentException("Only System.Func delegates are permitted.", "function");

            #if NETFX_CORE
            foreach (Type genericArgument in funcType.GenericTypeArguments)
            #else
            foreach (Type genericArgument in funcType.GetGenericArguments())
            #endif
                if (genericArgument != typeof(double))
                    throw new ArgumentException("Only doubles are supported as function arguments", "function");

            functionName = ConvertFunctionName(functionName);

            if (functions.ContainsKey(functionName) && !functions[functionName].IsOverWritable)
            {
                string message = string.Format("The function \"{0}\" cannot be overwriten.", functionName);
                throw new Exception(message);
            }

            #if NETFX_CORE
            int numberOfParameters = function.GetMethodInfo().GetParameters().Length;
            #else
            int numberOfParameters = function.Method.GetParameters().Length;
            #endif

            if (functions.ContainsKey(functionName) && functions[functionName].NumberOfParameters != numberOfParameters)
            {
                string message = string.Format("The number of parameters cannot be changed when overwriting a method.");
                throw new Exception(message);
            }

            FunctionInfo functionInfo = new FunctionInfo(functionName, numberOfParameters, isOverWritable, function);

            if (functions.ContainsKey(functionName))
                functions[functionName] = functionInfo;
            else
                functions.Add(functionName, functionInfo);
        }
        public SubscriberReference(Delegate action)
        {
            if (action == null)
                throw new ArgumentNullException("action");

            // If the delegates target is null, we can't hold a reference to it.
            // This happens when the callback method is static or a it has been 
            // created as a lambda/anonymous delegate that doesn't capture any 
            // instance variables. (Causes the compiler to generate a static method.)
            if (action.Target == null)
                throw new InvalidOperationException("Subscription with a static delegate method is not supported");

            _weakReference = new WeakReference(action.Target);
            _delegateType = action.GetType();
            _delegateMethod = action.GetMethodInfo();
        }
Exemple #9
0
        /// <summary>
        /// Initializes a new instance of <see cref="DelegateReference"/>.
        /// </summary>
        /// <param name="delegate">The original <see cref="Delegate"/> to create a reference for.</param>
        /// <param name="keepReferenceAlive">If <see langword="false" /> the class will create a weak reference to the delegate, allowing it to be garbage collected. Otherwise it will keep a strong reference to the target.</param>
        /// <exception cref="ArgumentNullException">If the passed <paramref name="delegate"/> is not assignable to <see cref="Delegate"/>.</exception>
        public DelegateReference(Delegate @delegate, bool keepReferenceAlive)
        {
            if (@delegate == null)
                throw new ArgumentNullException("delegate");

            if (keepReferenceAlive)
            {
                this._delegate = @delegate;
            }
            else
            {
                _weakReference = new WeakReference(@delegate.Target);
                _method = @delegate.GetMethodInfo();
                _delegateType = @delegate.GetType();
            }
        }
 /// <summary>
 /// Raises the event.
 /// </summary>
 /// <param name="handler">The delegate to invoke.</param>
 /// <param name="sender">The sender.</param>
 /// <param name="eventArgs">The <see cref="EventArgs"/> instance containing the event data.</param>
 public static void Raise(this Delegate handler, object sender, EventArgs eventArgs)
 {
     if (handler == null)
     {
         return;
     }
     try
     {
         handler.GetMethodInfo()
         .Invoke(handler.Target, new[] { TargetFactory.GetPair(sender), eventArgs });
     }
     catch (TargetInvocationException e)
     {
         throw new TargetInvocationException("Please check the inner exception for error details.", e.InnerException);
     }
 }
            private object[] GetArguments(Delegate valueFactory) {
                object[] arguments = new object[valueFactory.GetMethodInfo().GetParameters().Length];

                IEnumerable<ImportDefinition> ctorImportDefinitions = ImportDefinitions.Where(ReflectionModelServices.IsImportingParameter);
                foreach (ImportDefinition ctorImportDefinition in ctorImportDefinitions) {
                    ParameterInfo parameterInfo = ReflectionModelServices.GetImportingParameter(ctorImportDefinition).Value;
                    IEnumerable<Export> value;
                    if (_imports.TryGetValue(ctorImportDefinition, out value)) {
                        arguments[parameterInfo.Position] = value.Single().Value;
                        _imports.Remove(ctorImportDefinition);
                    } else {
                        throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "There is no export for parameter of type {0}",
                            parameterInfo.ParameterType));
                    }
                }

                return arguments;
            }
		/// <summary>
		/// Creates a CallbackFunction from a delegate.
		/// </summary>
		/// <param name="script">The script.</param>
		/// <param name="del">The delegate.</param>
		/// <param name="accessMode">The access mode.</param>
		/// <returns></returns>
		public static CallbackFunction FromDelegate(Script script, Delegate del, InteropAccessMode accessMode = InteropAccessMode.Default)
		{
			if (accessMode == InteropAccessMode.Default)
				accessMode = m_DefaultAccessMode;

#if NETFX_CORE
			MethodMemberDescriptor descr = new MethodMemberDescriptor(del.GetMethodInfo(), accessMode);
#else
			MethodMemberDescriptor descr = new MethodMemberDescriptor(del.Method, accessMode);
#endif
			return descr.GetCallbackFunction(script, del.Target);
		}
 private void storeMethodType(Delegate value)
 {
     if (value == null)
     {
         throw new DispatcherException ("EventDispatcher can't map something that isn't a delegate'", DispatcherExceptionType.ILLEGAL_CALLBACK_HANDLER);
     }
     #if NETFX_CORE
     MethodInfo methodInfo = value.GetMethodInfo();
     #else
     MethodInfo methodInfo = value.Method;
     #endif
     int argsLen = methodInfo.GetParameters ().Length;
     switch(argsLen)
     {
         case 0:
             callbackTypes[value] = EventCallbackType.NO_ARGUMENTS;
             break;
         case 1:
             callbackTypes[value] = EventCallbackType.ONE_ARGUMENT;
             break;
         default:
             throw new DispatcherException ("Event callbacks must have either one or no arguments", DispatcherExceptionType.ILLEGAL_CALLBACK_HANDLER);
     }
 }
        /// <summary>
        /// Removes a <see cref="Delegate"/> from the <see cref="WeakMulticastDelegate"/>.
        /// </summary>
        /// <param name="delegate">The <see cref="Delegate"/> to remove.</param>
        public void Remove(Delegate @delegate)
        {
            if (@delegate == null)
            return;

              for (int i = _delegates.Count - 1; i >= 0; i--)
              {
            InternalWeakDelegate weakDelegate = _delegates[i];
            if (weakDelegate.TargetReference != null)
            {
              // The delegate method is an object method.
              object target = weakDelegate.TargetReference.Target;
              if (target == null)
              {
            // Remove garbage collected entry.
            _delegates.RemoveAt(i);
              }
              else if (target == @delegate.Target
            #if !NETFX_CORE && !NET45
                  && weakDelegate.MethodInfo.Equals(@delegate.Method))
            #else
                  && weakDelegate.MethodInfo.Equals(@delegate.GetMethodInfo()))
            #endif

              {
            // Remove matching entry.
            _delegates.RemoveAt(i);
            break;
              }
            }
            else
            {
              // The delegate method is a class method.
              if (@delegate.Target == null
            #if !NETFX_CORE && !NET45
              && weakDelegate.MethodInfo.Equals(@delegate.Method))
            #else
              && weakDelegate.MethodInfo.Equals(@delegate.GetMethodInfo()))
            #endif
              {
            // Remove matching entry.
            _delegates.RemoveAt(i);
            break;
              }
            }
              }
        }
Exemple #15
0
 private static MethodInfo GetMethod(Delegate x)
 {
     return x.GetMethodInfo();
 }
Exemple #16
0
 /// <summary>
 /// Initializes a new instance of <see cref="WeakDelegate"/>
 /// </summary>
 /// <param name="delegate"></param>
 public WeakDelegate(Delegate @delegate)
 {
     _target = new WeakReference(@delegate.Target);
     _method = @delegate.GetMethodInfo();
 }
Exemple #17
0
 private void appendEventHandler(StringBuilder sb, String name, Delegate eh)
 {
     if (eh != null)
         sb.AppendFormat("{0}={1};", name, eh.GetMethodInfo().Name);
     else
         sb.AppendFormat("{0}=null;", name);
 }
Exemple #18
0
        /*!*/
        internal static MSA.Expression CallDelegate(Delegate/*!*/ method, MSA.Expression[]/*!*/ arguments)
        {
            MethodInfo methodInfo = method.GetMethodInfo();

            // We prefer to peek inside the delegate and call the target method directly. However, we need to
            // exclude DynamicMethods since Delegate.Method returns a dummy MethodInfo, and we cannot emit a call to it.
            if (methodInfo.DeclaringType == null || !methodInfo.DeclaringType.IsPublic() || !methodInfo.IsPublic) {
                // do not inline:
                return Ast.Call(AstUtils.Constant(method), method.GetType().GetMethod("Invoke"), arguments);
            }

            if (method.Target != null) {
                // inline a closed static delegate:
                if (methodInfo.IsStatic) {
                    return Ast.Call(null, method.GetMethodInfo(), ArrayUtils.Insert(AstUtils.Constant(method.Target), arguments));
                }

                // inline a closed instance delegate:
                return Ast.Call(AstUtils.Constant(method.Target), methodInfo, arguments);
            }

            // inline an open static delegate:
            if (methodInfo.IsStatic) {
                return Ast.Call(null, methodInfo, arguments);
            }

            // inline an open instance delegate:
            return Ast.Call(arguments[0], methodInfo, ArrayUtils.RemoveFirst(arguments));
        }
Exemple #19
0
    /// <summary>
    /// GetMethodName is not supported on some platforms.
    /// </summary>

#if REFLECTION_SUPPORT
#if !UNITY_EDITOR && NETFX_CORE
    static string GetMethodName(Callback callback)
    {
        System.Delegate d = callback as System.Delegate;
        return(d.GetMethodInfo().Name);
    }
Exemple #20
0
 /*!*/
 internal static LibraryOverload Reflect(Delegate/*!*/ overloadDelegate)
 {
     return Create(overloadDelegate, EncodeCustomAttributes(overloadDelegate.GetMethodInfo()));
 }
        //--------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="InternalWeakDelegate"/> class.
        /// </summary>
        /// <param name="delegate">
        /// The original <see cref="System.Delegate"/> to create a weak reference for.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="delegate"/> is <see langword="null"/>.
        /// </exception>
        public InternalWeakDelegate(Delegate @delegate)
        {
            if (@delegate == null)
            throw new ArgumentNullException("delegate");

              object target = @delegate.Target;
              TargetReference = (target != null) ? new WeakReference(target) : null;
            #if !NETFX_CORE && !NET45
              MethodInfo = @delegate.Method;
            #else
              MethodInfo = @delegate.GetMethodInfo();
            #endif

              DelegateType = @delegate.GetType();

              Debug.Assert(
            (TargetReference != null && !MethodInfo.IsStatic)
            || (TargetReference == null && MethodInfo.IsStatic),
            "Sanity check.");

              CheckForClosure(MethodInfo);
              CheckForNonPublicEventHandler(target, MethodInfo);
        }
Exemple #22
0
 public WeakDelegate( Delegate strongDelegate )
     : base( GetTarget( strongDelegate ) )
 {
     type = strongDelegate.GetType();
     method = strongDelegate.GetMethodInfo();
 }
Exemple #23
0
 static bool IsValid(Callback callback)
 {
     System.Delegate d = callback as System.Delegate;
     return(d != null && d.GetMethodInfo() != null);
 }
        /// <summary>
        /// Imports the delegate to the specified member.
        /// </summary>
        /// <param name="member">The member.</param>
        /// <param name="function">The function delegate.</param>
        /// <exception cref="System.ArgumentNullException">if member or function are null</exception>
        public static void Import(this IScriptObject script, string member, Delegate function)
        {
            if (member == null) throw new ArgumentNullException(nameof(member));
            if (function == null) throw new ArgumentNullException(nameof(function));

            script.SetValue(member, new ObjectFunctionWrapper(function.Target, function.GetMethodInfo()), true);
        }