I. Introduction
At the beginning of the work, delegates and events feel somewhat mysterious, and when you understand them, does not seem to feel quite that hard. The use of delegates and events in your project, you will find that he is great, this blog is considered myself a comb and a summary of the commission and events.
Second, the commission
Delegate in C #, C ++ is equivalent to the function pointer, but the delegate is an object oriented, is safe, is a special class, of course, he is a reference type, is a reference to delegate the transmission method.
2.1、delegate
Declare a delegate you must use the keyword "delegate", was commissioned by the first statement, instantiated. Parameter of at least 0, up to 32 parameters
Format is as follows:
private delegate string GetAsString();
A delegate is a class, instantiate an instance of the same with his class, but he will always accept a delegate method as a constructor parameter. There are two ways to call the delegate method, as follows:
int I = 10; var = Method new new getAsString (i.ToString); // call to a method Console.WriteLine ($ " Method Method The method of {()} "); // call the method two Console.WriteLine ($ " Method. Invoke method Method.invoke {()} ");
operation result:
2.2、Action
Action generic delegate is no return value, acceptable 0-16 incoming parameters
Action means no parameters and returns no value commissioned
Action <int, string> delegate incoming parameters expressed int, string no return value
Earlier we [ realized Log4Net logging ] in, on the use of Action. Such as:
public static void Debug(string message, Action RegistedProperties) { RegistedProperties(); log.Debug(message); }
Call for:
PFTLog.Debug ( " Test extension field ", () => { LogicalThreadContext.Properties [ " the LogType "] = " extension field contents "; });
In operation, the content can be run directly in Action.
2.3、Func
Func is returned generic delegate value, acceptable 0-16 incoming parameters
Func <int> represents no arguments, returns an int value entrusted
Func <object, string, int> parameter means that the incoming object, string returns an int value entrusted
public static decimal GetTotal(Func<int, int, decimal> func, int a, int b) { return func(a, b); }
Called
var total = GetTotal((a, b) => { return (decimal)a + b; }, 1, 2); Console.WriteLine($"结果为{total}");
operation result
2.4、predicate
bool return type of predicate generic delegate, but to accept a parameter passed
predicate <int> expressed its argument is int return bool delegate
Define a method:
public static bool FindPoints(int a) { return a >= 60; }
Definition of Predicate delegate
Predicate<int> predicate = FindPoints;
transfer
var points = new int[] { 10, 50, 60, 80, 100 }; var result = Array.FindAll(points, predicate); Console.WriteLine($"结果为{string.Join(";", result)}");
operation result
2.5, multicast delegate
The front contains only call a method of commission can contain multiple methods, this commission is called a multicast delegate. Multicast delegate using the "+ =" and - to add and delete commissioned two kinds operator "+."
Define two methods
public static void MultiplyByTwo ( Double V) { Double Result = V * 2; Console.WriteLine ($ " by value: {v}; MultiplyByTwo result Result} { "); } public static void Square ( Double V) { Double Result V * V =; Console.WriteLine ($ " by value: {v}; Square result result} { "); }
Then call
Action<double> operations = MultiplyByTwo;
operations(1);
operations += Square;
operations(2);
operation result:
Third, the event
The event is based on the principal for the commission to provide a publish / subscribe mechanism, declaring the event need to use the event keyword.
Publisher (Publisher): issuer of an event, also known as the sender (sender), is actually a object that maintains its own state information itself, when the information changes the state itself, will trigger an event, and notice that some event subscriber;
Subscribers (Subscriber): object of interest for the event, also known as Receiver, interested can register for the event, after the event the issuer trigger an event, it will automatically execute this code
Is not see the sender, it has a very familiar feeling! ! ! The first busy in a hurry, we look at events and use statement
There is such a scenario, if the system is abnormal, the need for timely notify the administrator. We need to record in our logs which added to notify the administrator functions, but the question is, how to notify the administrator of it? At least not now know. So we need to use in the event.
Add the following code, does not know if the logging can be referred to [ achieve Log4Net logging ]
// declare a delegate notice of public delegate void NoticeEventHander ( String the Message); // Under the mechanism entrusted us to establish a notification event public static Event NoticeEventHander OnNotice;
Called
public static void Debug ( String the Message, Action RegistedProperties) { RegistedProperties (); log.debug (the Message); // enforcement notice OnNotice .Invoke ($ "? system abnormalities, please timely processing, exception information: {} the Message "); }
In the code references the scene, notify the administrator to define a method of (here we direct Console.WriteLine out)
public static void Notice ( String Message) { Console.WriteLine ($ " Notify Message content} { "); }
To register, and then trigger the exception message
// Register a manner PFTLog.OnNotice + = Notice; // Register embodiment two //PFTLog.OnNotice + = new new PFTLog.NoticeEventHander (Notice); PFTLog.Debug ( " Test extension field ", () => { LogicalThreadContext.Properties [ " the LogType "] = " extension field contents "; });
operation result
There I just need to define a publisher, you can subscribe in any way, it is not very simple.
Understand the above events, we say that it is often the .Net object sender and EventArgs e
.Net Framework coding standards:
First, the name of the delegate type EventHandler should be to end
Second, the delegate prototype definition: void has a return value, and accepts two input parameters: a type Object, a EventArgs type (or inherited from EventArgs)
Third, the event is named after the EventHandler delegate remove the remaining part
Fourth, the type to be inherited from EventArgs EventArgs end
Now we have to customize a book launch event example
Create a corresponding class file:
Event by publishing the code:
public class BookInfoEventArgs : EventArgs { public BookInfoEventArgs(string bookName) { BookName = bookName; } public string BookName { get; set; } }
public class BookDealer { //泛型委托,定义了两个参数,一个是object sender,第二个是泛型 TEventArgs 的e //简化了如下的定义 //public delegate void NewBookInfoEventHandler(object sender, BookInfoEventArgs e); //public event NewBookInfoEventHandler NewBookInfo; public event EventHandler<BookInfoEventArgs> NewBookInfo; public void NewBook(string bookName) { RaiseNewBookInfo(bookName); } public void RaiseNewBookInfo(string bookName) { NewBookInfo?.Invoke(this, new BookInfoEventArgs(bookName)); } }
事件订阅者
public class Consumer { public Consumer(string name) { Name = name; } public string Name { get; set; } public void NewBookHere(object sender, BookInfoEventArgs e) { Console.WriteLine($"用户:{Name},收到书名为:{ e.BookName}"); } }
事件订阅和取消订阅
var dealer = new BookDealer(); var consumer1 = new Consumer("用户A"); dealer.NewBookInfo += consumer1.NewBookHere; dealer.NewBook("book112"); var consumer2 = new Consumer("用户B"); dealer.NewBookInfo += consumer2.NewBookHere; dealer.NewBook("book_abc"); dealer.NewBookInfo -= consumer1.NewBookHere; dealer.NewBook("book_all");
operation result
After this example, we can know Object sender parameter represents the event publisher itself, and EventArgs e is a surveillance target. After in-depth understanding, it is not that there is no imagination so difficult.
IV Summary
Here we are talking about delegates and events, the use of delegates and events in .Net development, can reduce dependence and coupling layer, the development of reusable components higher.