.NET事件 - 从预订一个事件阻止用户 [英] .NET events - blocking subscribers from subscribing on an event
本文介绍了.NET事件 - 从预订一个事件阻止用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我有一个处理器接口暴露的事件 - OnProcess。通常情况下,实现者做处理。因此,我可以放心地订阅此事件上,并确保它会被解雇。但一个处理器并不做处理 - 因此,我想阻止用户向所有本就可以了。我能做到这一点?在代码换句话说下面我想最后一行抛出一个异常:
VAR emptyProcessor =新EmptyProcessor();
emptyProcessor.OnProcess + = event_handler; //此行应该抛出一个异常。
解决方案
类EmptyProcessor :IProcessor {
[过时(EmptyProcessor.OnProcess不应该直接访问,真)]
公共事件的EventHandler OnProcess {
加{抛出新NotImplementedException(:( );}
拆下{}
}
}
在这种情况下,对过时的真正
参数导致编译时异常这样:
EmptyProcessor处理器1 =新EmptyProcessor();
IProcessor分享帮助=新EmptyProcessor();
processor1.OnProcess + =处理; //< - 编译时错误
processor2.OnProcess + =处理; //< - 运行时错误
Let's say I have a "Processor" interface exposing an event - OnProcess. Usually the implementors do the processing. Thus I can safely subscribe on this event and be sure it will be fired. But one processor doesn't do processing - thus I want to prevent subscribers to subscibe on it. Can I do that? In other words in the code below I want the last line to throw an exception:
var emptyProcessor = new EmptyProcessor();
emptyProcessor.OnProcess += event_handler; // This line should throw an exception.
解决方案
class EmptyProcessor : IProcessor {
[Obsolete("EmptyProcessor.OnProcess should not be directly accessed", true)]
public event EventHandler OnProcess {
add { throw new NotImplementedException(" :( "); }
remove { }
}
}
In this situation, the true
parameter on Obsolete causes a compile-time exception. so:
EmptyProcessor processor1 = new EmptyProcessor();
IProcessor processor2 = new EmptyProcessor();
processor1.OnProcess += handler; // <-- compile-time error
processor2.OnProcess += handler; // <-- run-time error
这篇关于.NET事件 - 从预订一个事件阻止用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文