Mos*_*she 8 c# events hook overriding subscribe
假设我有一个暴露事件的"处理器"接口 - OnProcess.通常,实现者进行处理.因此,我可以安全地订阅此事件,并确保它将被解雇.但是一个处理器不进行处理 - 因此我想阻止订阅者对其进行处理.我能这样做吗?换句话说,在下面的代码中,我希望最后一行抛出异常:
var emptyProcessor = new EmptyProcessor();
emptyProcessor.OnProcess += event_handler; // This line should throw an exception.
Run Code Online (Sandbox Code Playgroud)
class EmptyProcessor : IProcessor {
[Obsolete("EmptyProcessor.OnProcess should not be directly accessed", true)]
public event EventHandler OnProcess {
add { throw new NotImplementedException(" :( "); }
remove { }
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,trueObsolete上的参数会导致编译时异常.所以:
EmptyProcessor processor1 = new EmptyProcessor();
IProcessor processor2 = new EmptyProcessor();
processor1.OnProcess += handler; // <-- compile-time error
processor2.OnProcess += handler; // <-- run-time error
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |