gpt4 book ai didi

c# - 为什么我的自定义 OnLoaded 事件会收到 "Object reference not set to an instance of an object"?

转载 作者:太空宇宙 更新时间:2023-11-03 22:23:37 24 4
gpt4 key购买 nike

我需要做什么才能让这段代码正常工作?

我只是希望该类在完成加载时抛出一个事件,并让消费类对此使用react。

它在 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;
}
}
}

最佳答案

此代码在附加事件处理程序之前调用 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!
}

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

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

关于c# - 为什么我的自定义 OnLoaded 事件会收到 "Object reference not set to an instance of an object"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2229959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com