【问题标题】:C# event/delegate TargetInvocationException (WPF)C# 事件/委托 TargetInvocationException (WPF)
【发布时间】:2013-12-27 04:37:07
【问题描述】:

我正在玩活动/代表,但我经常收到以下错误:

“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)
{
}

【问题讨论】:

    标签: c# wpf events delegates targetinvocationexception


    【解决方案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
            }
        }
    

    【讨论】:

      【解决方案2】:

      您在方法调用之前缺少以下行

         TestEvent += new TestDelegate(TestMethod);
      

      构造函数中的正确代码应该是。

       public TestWindow()
              {
                  this.InitializeComponent();
      
                  TestEvent += new TestDelegate(TestMethod);
      
                  this.TestEvent(this, new EventArgs());
              }
      

      【讨论】:

      • -1 这不是原因,否则代码一开始就不会编译。
      • 这和编译有关系吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多