为什么我在自定义OnLoaded事件上得到“对象引用未设置为对象的实例”?

时间:2010-02-09 14:59:04

标签: c# events event-handling

如何使此代码正常工作?

我只是希望类在完成加载时抛出一个事件,并让消耗类对它做出反应。

OnLoaded上的错误表示它为空。

using System;
using System.Windows;

namespace TestEventLoaded8282
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            FileManager fm = new FileManager();
            fm.OnLoaded += new FileManager.LoadedHandler(fm_OnLoaded);
        }

        void fm_OnLoaded(object obj, FileManagerArgs args)
        {
            Console.WriteLine("the file manager is loaded: " + args.Message); 
        }
    }

    public class FileManager
    {
        public string Name { get; set; }

        public delegate void LoadedHandler(object obj, FileManagerArgs args);
        public event LoadedHandler OnLoaded;

        public FileManager()
        {
            Name = "this is the test file manager";
            OnLoaded(this, new FileManagerArgs("no errors"));
        }
    }

    public class FileManagerArgs : EventArgs
    {
        public string Message { get; set; }

        public FileManagerArgs(string message)
        {
            Message = message;
        }
    }
}

1 个答案:

答案 0 :(得分:4)

此代码在附加事件处理程序之前调用OnLoaded

public Window1() {
    InitializeComponent();
    FileManager fm = new FileManager();
   // The next line attaches a handler, but
   // not until the constructor finishes
}

执行以下操作:

public FileManager() {
        Name = "this is the test file manager";
        OnLoaded(this, new FileManagerArgs("no errors")); // No handler yet!
}

要解决此问题,请将侦听器委托作为FileManager构造函数参数,并在调用OnLoaded之前附加它:

public FileManager(LoadedHandler handler) {
        this.OnLoaded += handler;
        Name = "this is the test file manager";
        OnLoaded(this, new FileManagerArgs("no errors"));
}