[英]How can I make consuming custom events on my classes optional?
When I comment out the fm.OnLoaded
line below, it gives me an error that OnLoaded is null. 当我注释掉下面的
fm.OnLoaded
行时,它给出了一个OnLoaded为空的错误。
How can I make it optional for the caller of my class to consume the event or not as with .NET classes / events? 我如何使我的类的调用者可选择使用或不使用.NET类/事件?
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);
fm.Load();
}
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()
{}
public void Load()
{
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;
}
}
}
if (OnLoaded != null) {
OnLoaded(this, new FileManagerArgs("no errors"));
}
Check for null before invoking the delegate. 在调用委托之前检查null。 The following is a common pattern:
以下是一种常见模式:
public event EventHandler<FileManagerEventArgs> Loaded;
public void Load()
{
...
OnLoaded(new FileManagerEventArgs("no errors"));
}
protected virtual void OnLoaded(FileManagerEventArgs e)
{
EventHandler<FileManagerEventArgs> handler = this.Loaded;
if (handler != null)
{
handler(this, e);
}
}
You need to check that the OnLoaded
event handler is not null
before invoking it: 在调用
OnLoaded
事件处理程序之前,您需要检查它是否为null
:
LoadedHandler handler = OnLoaded;
if (handler != null)
{
handler(this, new FileManagerArgs("no errors"));
}
You will need to do this every time you invoke an event handler. 每次调用事件处理程序时都需要执行此操作。 The local
handler
variable above is to catch the case where you can check that the handler is non-null, but something removes the handler before you call it. 上面的本地
handler
变量用于捕获可以检查处理程序是否为空的情况,但在调用之前会删除处理程序。 Creating a local variable captures the handler to prevent this. 创建局部变量会捕获处理程序以防止这种情况发生。
An alternative approach is to define the event handler as: 另一种方法是将事件处理程序定义为:
public event LoadedHandler OnLoaded = delegate{};
This declares a default empty event handler, making the null check redundant (there is a slight performance loss using this approach though). 这声明了一个默认的空事件处理程序,使得空检查变得多余(尽管使用这种方法会有轻微的性能损失)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.