我正在用IronPython编写一个Python脚本,该脚本使用实现observer/observable pattern的C#DLL,C#库具有可观察的类,我想在Python中实现观察者。
我正在将我的Python函数注册为观察者方法,但是当它被调用时,我抛出了"System.MissingMemberException: 'PeripheralDiscoveredEventArgs' object has no attribute 'ChangeType'
异常。
使用here,here,here和here时,我找不到使用IronPython时如何在C#事件中使用自定义参数的任何文档。
我的Python代码是:
central = None
def MyCallback(sender, event_args):
print event_args.ChangeType, event_args.Name
def main():
global central
central = objFactory.GetCentral();
d = System.EventHandler[CustomEventArgs](MyCallback)
central.myHandler += d
(do something)
if __name__ == "__main__":
main()
我也尝试这样做:
central.myHandler += MyCallback
但是我有同样的例外。
在Central类中,将central
变量作为Central实例,并将其中的central.myHandler
属性定义为:
public event EventHandler<CustomEventArgs> myHandler = delegate { };
CustomEventArgs
类的定义为:
public class CustomEventArgs: EventArgs
{
public CustomEventArgs(Class1 obj1, int i, Class2 obj2, bool tf);
public Class1 Obj1 { get; }
public int I{ get; }
public Class2 Obj2t { get; }
public bool Tf{ get; }
}
调用我的回调的可观察类方法是:
internal abstract class EventHelper
{
internal static void TriggerEvent<T>(EventHandler<T> eventHandler, object source, T args)
{
// event handle no used ?
if (eventHandler == null) return;
try
{
// call event handler
eventHandler(source, args);
}
catch (Exception ex)
{
var target = eventHandler.Target != null ? eventHandler.Target : "unknown";
var methodName = (eventHandler.Method != null && eventHandler.Method.Name != null) ? eventHandler.Method.Name : "unknown";
Log.Error(string.Format("Exception in event handler '{0}' in '{1}'", methodName, target), ex);
}
}
整个例外是:
"System.MissingMemberException: 'CustomEventArgs' object has no attribute 'ChangeType'
at IronPython.Runtime.Binding.PythonGetMemberBinder.FastErrorGet`1.GetError(CallSite site, TSelfType target, CodeContext context)
at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
at __main__$1.MyCallback$74(PythonFunction $function, Object sender, Object event_args) in C:\\code\\Launcher.py:line 51
at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
at _Scripting_(Object[] , Object , CustomEventArgs )
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at EventHelper.TriggerEvent[T](EventHandler`1 eventHandler, Object source, T args) in C:\\code\\Utility\\EventHelper.cs:line 27"
是否有关于如何在IronPython中使用C#中的自定义事件参数的指针?谢谢!
环境:
答案 0 :(得分:0)
没关系,这是我的错误(与往常一样)。尝试访问类中不存在的成员通常会导致错误/异常...
只需将观察者代码更改为:
def centralOnPeripheralDiscovered_callback(sender, event_args):
print sender
print event_args
解决问题。感谢您的帮助!