Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 views
in Technique[技术] by (71.8m points)

c# - Why *should* we use EventHandler

I hate EventHandler. I hate that I have to cast the sender if I want to do anything with it. I hate that I have to make a new class inheriting from EventArgs to use EventHandler<T>.

I've always been told that EventHandler is the tradition and blah, blah...whatever. But I can't find a reason why this dogma is still around.

Is there a reason why it would be a bad idea to make a new delegate:

delegate void EventHandler<TSender, T>(TSender sender, T args);

That way the sender will be typesafe and I can pass whatever the heck I want as the arguments (including custom EventArgs if I so desire).

question from:https://stackoverflow.com/questions/3880789/why-should-we-use-eventhandler

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There actually is a good reason for requiring the second argument to derive from EventArgs if your fully-trusted code hosts third-party code as partially-trusted.

Because the callback to the event handling delegate is done in the context of the raising code and not the third party code, it is possible for malicious third-party code to add a privileged system operation as an event handler and thus potentially execute an escalation of privilege attack by running code in your fully-trusted context that their partially-trusted context could not run.

For example, if you declare a handler as type int -> void then the third-party code could enqueue YourEvent += Enviroment.Exit(-1) and have you exit the process unintentionally. This would obviously cause an easy-to-detect problem, but there are far more malicious APIs that could be enqueued to do other things.

When the signature is (object, EventArgs) -> void then there are no privileged operations in the framework that can be enqueued because none of them are compatible with this signature. It's part of the security code review in the framework to ensure this (unfortunately I cannot find the source where I read this).

So in certain circumstances there are valid security concerns as to why you should use the standard pattern. If you're 100% sure your code will never be used in these circumstances then the event signature guideline isn't as important (apart from other developers thinking WTF), but if it might be then you should follow it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...