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
186 views
in Technique[技术] by (71.8m points)

Need to understand how events work with delegates in C#

I cannot understand how delegates work with events in C#.

The form of the syntax is:

public event someNameDelegate someName;

control.someName += new control.someNameDelegate(methodName);

So how does it know what event (like mouse click etc) fires the method. I'm totally missing how this works. I understand that the delegate will call methodName but I don't understand for what event.

[Addittional Info] In the 2 lines above if someName is ContentModified then the code compiles In the 2 lines above if someName is Banana then the code does not compile.

However ContentModified is nowhere else in the code apart from the 2 line above:

So How does the compiler tell the difference?

question from:https://stackoverflow.com/questions/65845022/need-to-understand-how-events-work-with-delegates-in-c-sharp

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

1 Answer

0 votes
by (71.8m points)

For example, suppose you create a userControl and your control has a button, and when the button text changes, you define an event for it. That is, you see where the button text changes and there you define an event for it.

 public event TextChangedEventHandler ItemTextChanged;
 public delegate void TextChangedEventHandler(object Sender);




 private void btnContent_Click(object sender, RoutedEventArgs e)
 {
      if (ItemTextChanged != null)
      {
           ItemTextChanged(txtbChildBtn);
      }
 }

Same example with another name

public event ValueChangedEventHandler ItemValueChanged;
public delegate void ValueChangedEventHandler(object Sender);




private void btnContent_Click(object sender, RoutedEventArgs e)
{
   if (ItemValueChanged != null)
   {
       ItemValueChanged(sender);
   }
}

or FucosChanged button

 public event FucosEventHandler FucosChanged;
 public delegate void FucosEventHandler(object Sender, DependencyPropertyChangedEventArgs e);

 private void btnContent_FocusableChanged(object sender, , DependencyPropertyChangedEventArgs e)
 {
      if (FucosChanged != null)
      {
           FucosChanged(sender, e);
      }
 }

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

2.1m questions

2.1m answers

60 comments

57.0k users

...