我正在玩事件/委托,我经常收到以下错误:
类型为"System.Reflection.TargetInvocationException"的未处理异常发生在演示框架.dll
其他信息:调用目标已引发异常。
我的代码如下:
namespace Test
{
using System;
using System.Windows;
public partial class TestWindow : Window
{
public TestWindow()
{
this.InitializeComponent();
this.TestEvent(this, new EventArgs());
}
public delegate void TestDelegate(object sender, EventArgs e);
public event TestDelegate TestEvent;
}
}
显然,我在另一个位置有代码来打开 TestWindow 对象:
TestWindow testWindow = new TestWindow();
testWindow.TestEvent += this.TestMethod;
和:
private void TestMethod(object sender, EventArgs e)
{
}
你在构造函数中调用事件,这意味着在窗口初始化期间,所以TestEvent
在那个时候是空的。为TestEvent
添加一个空检查,并在构造函数以外的某种方法中调用它,检查TestEvent
是否分配了订阅者,即它不为空。
编辑:
下面是一些代码来演示:
public partial class TestWindow : Window
{
public TestWindow()
{
this.InitializeComponent();
//don't publish event in constructor, since the event yet to have any subscriber
//this.TestEvent(this, new EventArgs());
}
public void DoSomething()
{
//Do Something Here and notify subscribers that something has been done
if (TestEvent != null)
{
TestEvent(this, new EventArgs());
}
}
public delegate void TestDelegate(object sender, EventArgs e);
public event TestDelegate TestEvent;
}
public class Subscriber
{
public Subscriber(TestWindow win)
{
win.TestEvent += this.TestMethod;
}
private void TestMethod(object sender, EventArgs e)
{
//Do something when the event occurs
}
}
方法
调用之前缺少以下行
TestEvent += new TestDelegate(TestMethod);
构造函数中的正确代码是。
public TestWindow()
{
this.InitializeComponent();
TestEvent += new TestDelegate(TestMethod);
this.TestEvent(this, new EventArgs());
}