C #에서 내 이벤트를 어떻게 만들 수 있습니까?
C #에서 내 이벤트를 어떻게 만들 수 있습니까?
다음은 C #으로 이벤트를 만들고 사용하는 예입니다.
using System;
namespace Event_Example
{
//First we have to define a delegate that acts as a signature for the
//function that is ultimately called when the event is triggered.
//You will notice that the second parameter is of MyEventArgs type.
//This object will contain information about the triggered event.
public delegate void MyEventHandler(object source, MyEventArgs e);
//This is a class which describes the event to the class that recieves it.
//An EventArgs class must always derive from System.EventArgs.
public class MyEventArgs : EventArgs
{
private string EventInfo;
public MyEventArgs(string Text)
{
EventInfo = Text;
}
public string GetInfo()
{
return EventInfo;
}
}
//This next class is the one which contains an event and triggers it
//once an action is performed. For example, lets trigger this event
//once a variable is incremented over a particular value. Notice the
//event uses the MyEventHandler delegate to create a signature
//for the called function.
public class MyClass
{
public event MyEventHandler OnMaximum;
private int i;
private int Maximum = 10;
public int MyValue
{
get
{
return i;
}
set
{
if(value <= Maximum)
{
i = value;
}
else
{
//To make sure we only trigger the event if a handler is present
//we check the event to make sure it's not null.
if(OnMaximum != null)
{
OnMaximum(this, new MyEventArgs("You've entered " +
value.ToString() +
", but the maximum is " +
Maximum.ToString()));
}
}
}
}
}
class Program
{
//This is the actual method that will be assigned to the event handler
//within the above class. This is where we perform an action once the
//event has been triggered.
static void MaximumReached(object source, MyEventArgs e)
{
Console.WriteLine(e.GetInfo());
}
static void Main(string[] args)
{
//Now lets test the event contained in the above class.
MyClass MyObject = new MyClass();
MyObject.OnMaximum += new MyEventHandler(MaximumReached);
for(int x = 0; x <= 15; x++)
{
MyObject.MyValue = x;
}
Console.ReadLine();
}
}
}
이벤트 기사 에서 이벤트 및 대리인에 대한 전체 토론이 있습니다 . 가장 간단한 종류의 이벤트의 경우 공개 이벤트를 선언하면 컴파일러가 이벤트와 필드를 모두 만들어 구독자를 추적합니다.
public event EventHandler Foo;
보다 복잡한 가입 / 가입 취소 논리가 필요한 경우 다음과 같이 명시 적으로 수행 할 수 있습니다.
public event EventHandler Foo
{
add
{
// Subscription logic here
}
remove
{
// Unsubscription logic here
}
}
다음 코드를 사용하여 이벤트를 선언 할 수 있습니다.
public event EventHandler MyOwnEvent;
필요한 경우 EventHandler 대신 사용자 정의 대리자 유형을 사용할 수 있습니다.
이벤트 자습서 (MSDN) 기사에서 .NET의 이벤트 사용에 대한 자세한 정보 / 자습을 찾을 수 있습니다 .
이를 위해서는 세 가지 구성 요소를 알아야합니다
- 책임있는 곳
firing the Event
- 책임있는 곳
responding to the Event
이벤트 자체
ㅏ. 행사
b. EventArgs
씨. EventArgs 열거
now lets create Event that fired when a function is called
but I my order of solving this problem like this: I'm using the class before I create it
the place responsible for
responding to the Event
NetLog.OnMessageFired += delegate(object o, MessageEventArgs args) { // when the Event Happened I want to Update the UI // this is WPF Window (WPF Project) this.Dispatcher.Invoke(() => { LabelFileName.Content = args.ItemUri; LabelOperation.Content = args.Operation; LabelStatus.Content = args.Status; }); };
NetLog is a static class I will Explain it later
the next step is
the place responsible for
firing the Event
//this is the sender object, MessageEventArgs Is a class I want to create it and Operation and Status are Event enums NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Started)); downloadFile = service.DownloadFile(item.Uri); NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Finished));
the third step
- the Event itself
I warped The Event within a class called NetLog
public sealed class NetLog
{
public delegate void MessageEventHandler(object sender, MessageEventArgs args);
public static event MessageEventHandler OnMessageFired;
public static void FireMessage(Object obj,MessageEventArgs eventArgs)
{
if (OnMessageFired != null)
{
OnMessageFired(obj, eventArgs);
}
}
}
public class MessageEventArgs : EventArgs
{
public string ItemUri { get; private set; }
public Operation Operation { get; private set; }
public Status Status { get; private set; }
public MessageEventArgs(string itemUri, Operation operation, Status status)
{
ItemUri = itemUri;
Operation = operation;
Status = status;
}
}
public enum Operation
{
Upload,Download
}
public enum Status
{
Started,Finished
}
this class now contain the Event
, EventArgs
and EventArgs Enums
and the function
responsible for firing the event
sorry for this long answer
참고URL : https://stackoverflow.com/questions/623451/how-can-i-make-my-own-event-in-c
'programing tip' 카테고리의 다른 글
객체 속성으로 배열에서 객체 제거 (0) | 2020.07.19 |
---|---|
Maven을 사용하여 릴리스 종속성을 강제로 다시 다운로드 (0) | 2020.07.19 |
Xcode 8 Beta 4-댓글 바로 가기 비활성화 (0) | 2020.07.19 |
Javascript Ternary 연산자를 사용한 연산자 우선 순위 (0) | 2020.07.19 |
Android에서 뷰의 전역 스타일 설정 (0) | 2020.07.19 |