简体   繁体   中英

C# EventHandler Question

Quick question regarding EventHandlers in C#, let's say we have the following code:

MyObject.MyEventHandler += (...)

I am currently refactoring some code, and the (...) is often replaced with another eventhandler, as such :

EventHandler A;

Test()
{    
   A += A_Method;
   MyObject.MyEventHandler += A       
}

Wouldn't it be simpler to disregard "A" and just write instead:

Test()
{    
   MyObject.MyEventHandler += A_Method;       
}

What is the use of EventHandler "A", if we can just directly pass the method to the EventHandler object from "MyObject" ?

Thanks !

Sure, as long as A isn't used other places. Otherwise it might have been a refactoring to reduce code duplication.

I assume you mean

A += A_Method;
MyObject.MyEventHandler += A;

(without parentheses after A_Method). If so, assuming that there is nothing more complex around this than the example, A can probably be safely omitted. When refactoring, F12 (go to definition) is your friend: find all references and make sure they all are properly re-routed, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM