开发者

C# event handler explanation please

开发者 https://www.devze.com 2023-03-28 12:16 出处:网络
Could anyone please explain what and how this code below is doing/working? RoleEnvironment.Chaning += RoleEnvironmentChaning;

Could anyone please explain what and how this code below is doing/working?

RoleEnvironment.Chaning += RoleEnvironmentChaning;

private void RoleEnvironmentChanaing(object sender, RoleEnvironmentchaningnEventArgs e)
{
  ......
}

basically, if you could walk me through how event handling works in c#.n开发者_StackOverflow中文版et will be greatly appreciated. Thanks.


Let's forget about C# for a second and think about the following scenario. You have a button on the screen that you want the user to click, you don't know when the user will click the button and neither do you want to check constantly if the user has clicked the button. What you want to do is run a bit of custom code when the user does eventually click on a button.

Welcome to events or delegates.

Let's take a look at the button. The Button has a Click event that you can hook your custom code onto. i.e.

//This happens in the designer
Button button = new Button();
button.Click += new EventHandler(YourMethod);

Your method will now be called once the button has been clicked.

What happens on Click of the button? Someone will check whether or not there are subscribers to the event

if(Click != null)
{
   Click(this, someEventArguments);
}


Basically that's saying: whenever the RoleEnviroment decided to trigger the "changing" event, call that method. (I assume it should be Changing rather than Chaning or Chanaing as per your code.)

In other words, events in C# are an implementation of the publisher/subscriber or observer pattern.

See my article on events and delegates for more information.


Some first page search results:

http://www.codeproject.com/KB/cs/csevents01.aspx

http://www.c-sharpcorner.com/UploadFile/ddutta/EventHandlingInNetUsingCS11092005052726AM/EventHandlingInNetUsingCS.aspx

http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消