C# Event & delegate
Unity3D/C# 2019. 1. 23. 00:17반응형
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | using System; namespace ConsoleApp3 { class Program { static void Main(string[] args) { var video = new Video() { Title = "Video 1" }; var videoEncoder = new VideoEncoder(); //Publisher var mailService = new MailService(); //Subscriber var messageService = new MessageService(); videoEncoder.VideoEncoded += mailService.OnVideoEncoded; videoEncoder.VideoEncoded += messageService.OnVideoEncoded; videoEncoder.Encode(video); Console.ReadLine(); } } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace ConsoleApp3 { public class VideoEventArgs : EventArgs { public Video Video { get; set; } } public class VideoEncoder { // 1. 델리게이트 정의 // 2. 델리게이트기반의 이벤트 정의 // 3. 이벤트 실행 public delegate void VideoEncodedEventHandler(object source, VideoEventArgs arg); //public event VideoEncodedEventHandler VideoEncoded; public event EventHandler<VideoEventArgs> VideoEncoded; //public event EventHandler VideoEncoded; public void Encode(Video video) { Console.WriteLine("Encoding Video..."); Thread.Sleep(3000); OnVideoEncoded(video); } protected virtual void OnVideoEncoded(Video video) { if (VideoEncoded != null) { VideoEncoded(this, new VideoEventArgs() {Video = video}); } } } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 | using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp3 { public class Video { public string Title { get; set; } } } | cs |
1 2 3 4 5 6 7 8 9 10 11 | using System; namespace ConsoleApp3 { public class MailService { public void OnVideoEncoded(object source, VideoEventArgs args) { Console.WriteLine("MailingService: Sending an email..." + args.Video.Title); } } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 | using System; namespace ConsoleApp3 { public class MessageService { public void OnVideoEncoded(object source, VideoEventArgs args) { Console.WriteLine("MessageService: Sending a text message..." + args.Video.Title); } } } | cs |
반응형
'Unity3D > C#' 카테고리의 다른 글
CLR(Common Language Runtime) (0) | 2019.03.12 |
---|---|
C# Generic (0) | 2019.01.23 |
ReSharper (0) | 2019.01.23 |
C# Split List (0) | 2019.01.22 |
What and where are the stack and heap? (0) | 2019.01.18 |