如何动态调用事件

时间:2012-10-15 13:33:02

标签: c# delegates

我有一个项目,在那个项目中我动态加载了一个dll。它看起来像:

 AssemblyPart assemblyPart = new AssemblyPart();
 WebClient downloader = new WebClient();
 string path = string.Format("../ClientBin/{0}.xap", "AgileTax");
 downloader.OpenReadCompleted += (e, sa) =>
        {
getdllinStream = GetStream(sa.Result, _CurReturnType.PackageName + "ERC", true);
_formsAssembly = assemblyPart.Load(getdllinStream);
 foreach (var item in _formsAssembly.GetTypes())
                    {
                        if (item.FullName == _CurReturnType.PackageName + "ERC.State.StateMain")
                        {
                            ATSpgm = item;
                        }
                    }
  var class_instance = _formsAssembly1.CreateInstance(PackageName + "ERC.State.StateMain");
if (class_instance != null)
            {

                MethodInfo[] infomem = ATSpgm.GetMethods();
                MethodInfo SetVarDllNG1 = ATSpgm.GetMethod("ProcessERC");
                SetVarDllNG1.Invoke(class_instance, parametersArray);
          }
         }
 downloader.OpenReadAsync(new Uri(path, UriKind.Relative));

现在我的问题是在.dll中我的代码如下:

  public event ERCErrorHandling OnERCErrorHandler;
  public delegate string ERCErrorHandling(Exception ex);

现在我的问题是如何在上面调用这个ERCErrorHandling事件,我调用了像ProcessERC这样的方法。

1 个答案:

答案 0 :(得分:1)

事件只是MulticastDelegate类型的字段。这意味着您可以使用这些说明获取它:

        FieldInfo anEvn = item.GetType().GetField("OnERCErrorHandler",
           System.Reflection.BindingFlags.Instance |
           System.Reflection.BindingFlags.NonPublic) as FieldInfo;
        if (anEvn != null)
            MulticastDelegate mDel = anEvn.GetValue(item) as MulticastDelegate;

然后,您可以使用GetInvokationList()获取附加到事件的单个代理。每个委托都有一个Target(将执行该方法的对象)和Method。你可以循环执行它们。当然,您必须知道预期的参数才能将它们传递给Invoke:

                Delegate[] dels = mDel.GetInvocationList();
                object[] parms = new object[1];
                parms[0] = null; // you must create the Exception you want to pass as argument here
                foreach (Delegate aDel in dels)
                    aDel.Method.Invoke(aDel.Target, parms);