C# 이벤트
6147 단어 dotnetcsharpprogrammingbeginners
Program.cs
using Events;
var alarm = new Alarm(1000);
alarm.OnAlarmRing += HandleOnAlarmEvent;
await alarm.Start();
void HandleOnAlarmEvent(object sender, AlarmEventArgs e)
{
System.Console.WriteLine("Alarm Finished");
System.Console.WriteLine($"Message : {e.Message}");
}
Alarm.cs
namespace Events
{
public class AlarmEventArgs : EventArgs
{
public AlarmEventArgs(string message)
{
Message = message;
}
public string Message { get; set; }
}
// Biz EventArgs Ni o'zimiz majburlab boshqa type oladigan qildik xo'sh
// endi EventHandler ni Generik qilishimiz kerak
public class Alarm
{
// Event elon qilish
// public delegate void AlarmRingEvent();
// public event AlarmRingEvent OnAlarmRing;
public event EventHandler<AlarmEventArgs> OnAlarmRing;
// ----------------------------------------------
public int Time { get; set;}
public Alarm(int time)
{
Time = time;
}
public async Task Start()
{
var now = DateTime.Now;
await Task.Delay(Time);
// OnAlarmRing?.Invoke();
OnAlarmRing?.Invoke(this, new AlarmEventArgs($"Time is up : {DateTime.Now}"));
}
}
}
/*
EventArgs - Event bilan jo'natilishi kerak bo'lgan ma'lumotlarni Encapsulate qilib jo'natadi
EventArgs - ichida hech narsa yo'q Faqat Inheritance uchun ishlatiladi
object sender - Publish qilayotgan objectni o'zi
*/
Result
Alarm Finished
Message : Time is up : 5/12/2022 5:58:00 PM
Reference
이 문제에 관하여(C# 이벤트), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/xakimov_dev/c-events-52gh텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)