Created
January 7, 2018 23:19
-
-
Save luisdeol/dbac402fa87ca3f4689883d2bf4b649f to your computer and use it in GitHub Desktop.
Custom event accessors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| namespace create_implement_events_callbacks | |
| { | |
| public class MyArgs : EventArgs | |
| { | |
| public MyArgs(int value) | |
| { | |
| Value = value; | |
| } | |
| public int Value { get; set; } | |
| } | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| var pub = new Publisher(); | |
| pub.OnChange += (sender, e) => Console.WriteLine($"Event raised: {e.Value}"); | |
| pub.OnChange += (sender, e) => Console.WriteLine($"Event raised: {e.Value}"); | |
| pub.Raise(); | |
| Console.ReadKey(); | |
| } | |
| } | |
| public class Publisher | |
| { | |
| private event EventHandler<MyArgs> _onChange = delegate { }; | |
| public event EventHandler<MyArgs> OnChange | |
| { | |
| add | |
| { | |
| lock (_onChange) | |
| { | |
| _onChange += value; | |
| } | |
| } | |
| remove | |
| { | |
| lock (_onChange) | |
| { | |
| _onChange -= value; | |
| } | |
| } | |
| } | |
| public void Raise() | |
| { | |
| _onChange(this, new MyArgs(30)); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment