简体   繁体   English

传递和解释参数-动态处理程序

[英]Passing & Interpreting Parameters - Dynamic Handlers

I have a relatively dynamic event process and I need to be able to interpret parameters passed to a dynamic handler, but I am having trouble doing just that. 我有一个相对动态的事件流程,我需要能够解释传递给动态处理程序的参数,但是我很难做到这一点。

Please note that the code below is 100% functional as is. 请注意,以下代码按原样100%起作用。 It simply needs to be adjusted to meet requirements. 只需调整它即可满足要求。

Below is a simple class that defines an Action and Event. 下面是一个定义Action和Event的简单类。 The OnLeftClickEvent() method receives an object[] of args which due to event constraints, must be encapsulated in EventArgs. OnLeftClickEvent()方法接收args的object [],由于事件限制,它们必须封装在EventArgs中。

public class SomeSubscriber : SubscriberBase
{
    private Logger<SomeSubscriber> debug = new Logger<SomeSubscriber>();

    public Action LeftClickAction;
    public event EventHandler LeftClickEvent;

    public SomeSubscriber()
    {
        LeftClickAction += OnLeftClickEvent;
    }

    public void OnLeftClickEvent(params object[] args)
    {
        AppArgs eventArgs = new AppArgs(this, args);

        if(LeftClickEvent != null) LeftClickEvent(this, eventArgs);
    }
} 

On the receiving end is the class that implements the dynamic handler and triggers the event: 在接收端是实现动态处理程序并触发事件的类:

public class EventControllBase : _MonoControllerBase
{
    private Logger<EventControllBase> debug = new Logger<EventControllBase>();

    SomeSubscriber subscriber;

    private void Start()
    {
        subscriber = new SomeSubscriber();

        subscriber.AddHandler("LeftClickEvent", e =>
        {
            debug.LogWarning( string.Format("Received {0} from {1} ", e[1], e[0]) );
            return true;
        });
    }

    private void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {   // Trigger events.
            subscriber.InvokeDelegate("LeftClickAction", (object) new object[]{ this, Input.mousePosition });
        }
    }
}

In the Start() method I define a dynamic handler and in Update() it is triggered and desired data is passed. 在Start()方法中,我定义了一个动态处理程序,在Update()中,它被触发并传递了所需的数据。

e[1] is obviously of type EventArgs (AppArgs:EventArgs to be specific) but I'm not sure how to access the members to get data within the instance. e [1]显然是EventArgs类型(具体来说是AppArgs:EventArgs),但是我不确定如何访问成员以获取实例中的数据。 I've tried casting but it was a no go. 我已经尝试过投放,但这是不行的。

Here is the body of AppArgs if it helps: 如果有帮助,这是AppArgs的正文:

public class AppArgs : EventArgs
{
public object sender {get; private set;}
private object[] _args;

public AppArgs(object sender, object[] args)
{
    this.sender = sender;
    this._args = args;
}

public object[] args()
{
    return this._args;
}
}

Dynamic Handler 动态处理程序

public static class DynamicHandler
{
        /// <summary>
        /// Invokes a static delegate using supplied parameters.
        /// </summary>
        /// <param name="targetType">The type where the delegate belongs to.</param>
        /// <param name="delegateName">The field name of the delegate.</param>
        /// <param name="parameters">The parameters used to invoke the delegate.</param>
        /// <returns>The return value of the invocation.</returns>
        public static object InvokeDelegate(this Type targetType, string delegateName, params object[] parameters)
        {
            return ((Delegate)targetType.GetField(delegateName).GetValue(null)).DynamicInvoke(parameters);
        }

        /// <summary>
        /// Invokes an instance delegate using supplied parameters.
        /// </summary>
        /// <param name="target">The object where the delegate belongs to.</param>
        /// <param name="delegateName">The field name of the delegate.</param>
        /// <param name="parameters">The parameters used to invoke the delegate.</param>
        /// <returns>The return value of the invocation.</returns>
        public static object InvokeDelegate(this object target, string delegateName, params object[] parameters)
        {
            return ((Delegate)target.GetType().GetField(delegateName).GetValue(target)).DynamicInvoke(parameters);
        }

        /// <summary>
        /// Adds a dynamic handler for a static delegate.
        /// </summary>
        /// <param name="targetType">The type where the delegate belongs to.</param>
        /// <param name="fieldName">The field name of the delegate.</param>
        /// <param name="func">The function which will be invoked whenever the delegate is invoked.</param>
        /// <returns>The return value of the invocation.</returns>
        public static Type AddHandler(this Type targetType, string fieldName,
            Func<object[], object> func)
        {
            return InternalAddHandler(targetType, fieldName, func, null, false);
        }

        /// <summary>
        /// Adds a dynamic handler for an instance delegate.
        /// </summary>
        /// <param name="target">The object where the delegate belongs to.</param>
        /// <param name="fieldName">The field name of the delegate.</param>
        /// <param name="func">The function which will be invoked whenever the delegate is invoked.</param>
        /// <returns>The return value of the invocation.</returns>
        public static Type AddHandler(this object target, string fieldName,
            Func<object[], object> func)
        {
            return InternalAddHandler(target.GetType(), fieldName, func, target, false);
        }

        /// <summary>
        /// Assigns a dynamic handler for a static delegate or event.
        /// </summary>
        /// <param name="targetType">The type where the delegate or event belongs to.</param>
        /// <param name="fieldName">The field name of the delegate or event.</param>
        /// <param name="func">The function which will be invoked whenever the delegate or event is fired.</param>
        /// <returns>The return value of the invocation.</returns>
        public static Type AssignHandler(this Type targetType, string fieldName,
            Func<object[], object> func)
        {
            return InternalAddHandler(targetType, fieldName, func, null, true);
        }

        /// <summary>
        /// Assigns a dynamic handler for a static delegate or event.
        /// </summary>
        /// <param name="target">The object where the delegate or event belongs to.</param>
        /// <param name="fieldName">The field name of the delegate or event.</param>
        /// <param name="func">The function which will be invoked whenever the delegate or event is fired.</param>
        /// <returns>The return value of the invocation.</returns>
        public static Type AssignHandler(this object target, string fieldName, Func<object[], object> func)
        {
            return InternalAddHandler(target.GetType(), fieldName, func, target, true);
        }

        private static Type InternalAddHandler(Type targetType, string fieldName,
            Func<object[], object> func, object target, bool assignHandler)
        {
            Type delegateType;
            var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic |
                               (target == null ? BindingFlags.Static : BindingFlags.Instance);
            var eventInfo = targetType.GetEvent(fieldName, bindingFlags);
            if (eventInfo != null && assignHandler)
                throw new ArgumentException("Event can be assigned.  Use AddHandler() overloads instead.");

            if (eventInfo != null)
            {
                delegateType = eventInfo.EventHandlerType;
                var dynamicHandler = BuildDynamicHandler(delegateType, func);
                eventInfo.GetAddMethod(true).Invoke(target, new Object[] { dynamicHandler });
            }
            else
            {
                var fieldInfo = targetType.GetField(fieldName);
                                                    //,target == null ? BindingFlags.Static : BindingFlags.Instance);
                delegateType = fieldInfo.FieldType;
                var dynamicHandler = BuildDynamicHandler(delegateType, func);
                var field = assignHandler ? null : target == null
                                ? (Delegate)fieldInfo.GetValue(null)
                                : (Delegate)fieldInfo.GetValue(target);
                field = field == null
                            ? dynamicHandler
                            : Delegate.Combine(field, dynamicHandler);
                if (target != null)
                    target.GetType().GetField(fieldName).SetValue(target, field);
                else
                    targetType.GetField(fieldName).SetValue(null, field);
                    //(target ?? targetType).SetFieldValue(fieldName, field);
            }
            return delegateType;
        }

        /// <summary>
        /// Dynamically generates code for a method whose can be used to handle a delegate of type 
        /// <paramref name="delegateType"/>.  The generated method will forward the call to the
        /// supplied <paramref name="func"/>.
        /// </summary>
        /// <param name="delegateType">The delegate type whose dynamic handler is to be built.</param>
        /// <param name="func">The function which will be forwarded the call whenever the generated
        /// handler is invoked.</param>
        /// <returns></returns>
        public static Delegate BuildDynamicHandler(this Type delegateType, Func<object[], object> func)
        {
            var invokeMethod = delegateType.GetMethod("Invoke");
            var parameters = invokeMethod.GetParameters().Select(parm =>
                Expression.Parameter(parm.ParameterType, parm.Name)).ToArray();
            var instance = func.Target == null ? null : Expression.Constant(func.Target);
            var convertedParameters = parameters.Select(parm => Expression.Convert(parm, typeof(object))).Cast<Expression>().ToArray();
            var call = Expression.Call(instance, func.Method, Expression.NewArrayInit(typeof(object), convertedParameters));
            var body = invokeMethod.ReturnType == typeof(void)
                ? (Expression)call
                : Expression.Convert(call, invokeMethod.ReturnType);
            var expr = Expression.Lambda(delegateType, body, parameters);
            return expr.Compile();
        }
    }

So I managed to solve my issue, below are all the modifications I made to the code above: 所以我设法解决了我的问题,下面是我对上面的代码所做的所有修改:

First off I made some slight modifications to AppArgs that are pretty self explanatory: 首先,我对AppArgs进行了一些细微的修改,这些修改很容易说明:

public class AppArgs : EventArgs
{
    public object sender {get; private set;}
    public object[] args {get; private set;}

    public AppArgs(object sender, object[] args)
    {
        this.sender = sender;
        this.args = args;
    }
}

Next step was to figure out how to properly cast my EventArgs object[] back to an AppArgs: 下一步是弄清楚如何正确地将EventArgs object []强制转换回AppArgs:

In EventControllBase.Start() EventControllBase.Start()中

    private void Start()
    {
        subscriber = new SomeSubscriber();

        subscriber.AddHandler("LeftClickEvent", e =>
        {   
            debug.LogWarning( string.Format("Received {0} from {1} ", ( (AppArgs)e[1] ).args[1], e[0]) );
            return true;
        });
    }

To clarify, I simply had to cast e[1] in the proper manner like so: ( (AppArgs)e[1] ) 为了澄清起见,我只需要像这样正确地转换e [1]即可:((AppArgs)e [1])

I can now freely access the members of AppArgs the way I need to. 现在,我可以按需要自由访问AppArgs的成员。 Thank you all for your help, it is very much appreciated. 谢谢大家的帮助,非常感谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM