Предаване и интерпретиране на параметри - динамични манипулатори

Имам сравнително динамичен процес на събитие и трябва да мога да интерпретирам параметри, предадени на динамичен манипулатор, но имам проблеми с това.

Моля, обърнете внимание, че кодът по-долу е 100% функционален такъв, какъвто е. Просто трябва да се коригира, за да отговаря на изискванията.

По-долу е даден прост клас, който дефинира действие и събитие. Методът OnLeftClickEvent() получава обект [] от аргументи, които поради ограниченията на събитията трябва да бъдат капсулирани в 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);
    }
} 

На приемащия край е класът, който имплементира динамичния манипулатор и задейства събитието:

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 });
        }
    }
}

В метода Start() дефинирам динамичен манипулатор и в Update() той се задейства и желаните данни се предават.

e[1] очевидно е от тип EventArgs (AppArgs:EventArgs, за да бъдем конкретни), но не съм сигурен как да осъществя достъп до членовете, за да получа данни в рамките на екземпляра. Опитах кастинг, но не се получи.

Ето тялото на 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;
}
}

Динамичен манипулатор

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();
        }
    }

person Nestor Ledon    schedule 22.06.2013    source източник
comment
Вашият Subscriber клас няма AddHandler метод, така че това няма да работи в момента. Можете да използвате subscriber.LeftClickEvent += ... - но честно казано не е ясно защо изобщо имате клас Subscriber. Какво добавя към това, което .NET вече предоставя с делегати и събития?   -  person Jon Skeet    schedule 22.06.2013
comment
@Jon Вероятно е наследено от SubscriberBase. @Xerosigma Можете ли да включите внедряването на AddHandler?   -  person Mike Precup    schedule 22.06.2013
comment
@MikePrecup: А, пропуснах това, да. Все още изобщо не ми е ясно каква е целта на това... изглежда, че преоткрива колелото.   -  person Jon Skeet    schedule 22.06.2013
comment
@MikePrecup Добавих внедряването на AddHandler най-отдолу, съжалявам за погрешното насочване. И благодаря за отделеното време.   -  person Nestor Ledon    schedule 22.06.2013
comment
@JonSkeet За да обясни модела, класът My Subscriber ще може да улавя аргументи в метода OnLeftClickEvent(), преди да се задейства Handler. По този начин мога първо да стартирам специфична за обект логика, след което да получа резултата/изхода, от който се нуждая, обратно в повикващия. Благодаря за вашето мнение.   -  person Nestor Ledon    schedule 22.06.2013
comment
Редактирах ти заглавието. Моля, вижте Трябва ли въпросите да включват „тагове“ в заглавията си?, където консенсусът е „не“, не трябва.   -  person John Saunders    schedule 23.06.2013
comment
@JohnSaunders, благодаря! Добро четене също.   -  person Nestor Ledon    schedule 23.06.2013


Отговори (1)


Така че успях да разреша проблема си, по-долу са всички модификации, които направих в кода по-горе:

Първо направих някои леки модификации на 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;
    }
}

Следващата стъпка беше да разбера как правилно да прехвърля моя EventArgs обект [] обратно към AppArgs:

В 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;
        });
    }

За да изясня, просто трябваше да прехвърлям e[1] по правилния начин така: ( (AppArgs)e[1] )

Вече имам свободен достъп до членовете на AppArgs по начина, по който трябва. Благодаря на всички за помощта, много я оценявам.

person Nestor Ledon    schedule 22.06.2013