我正在玩事件/代表,我经常遇到以下错误:
发生了'System.Reflection.TargetInvocationException'类型的未处理异常 PresentationFramework.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)
{
}
答案 0 :(得分:1)
您正在构造函数中调用该事件,这意味着在窗口初始化期间,因此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
}
}
答案 1 :(得分:-1)
您在方法调用之前缺少以下行
TestEvent += new TestDelegate(TestMethod);
构造函数中的正确代码是。
public TestWindow()
{
this.InitializeComponent();
TestEvent += new TestDelegate(TestMethod);
this.TestEvent(this, new EventArgs());
}