Take a look at the code first:
/// <summary> ///event class/// </summary> Public classEventClass {/// <summary> ///Go Delegate/// </summary> /// <param name= "Nam" ></param> Public Delegate voidGo (stringNam); /// <summary> ///Event Delegate/// </summary> Public EventGo goevent; /// <summary> ///Method 1/// </summary> /// <param name= "name" ></param> Public voidGofun (stringname) {Console.WriteLine (name); } /// <summary> ///Method 2/// </summary> /// <param name= "name" ></param> Public voidGoFun2 (stringname) {Console.WriteLine (name+"fun2"); } /// <summary> ///test Method/// </summary> Public voidTest () {//event does not need new initializationGo + = Gofun;//ErrorGoevent + = Gofun;//SuccessGo Go=NewGo (Gofun);//SuccessGoevent + = GoFun2;//SuccessGo + = GoFun2;//Success//execution-Consistent results (no difference)Goevent ("Test"); Go ("Test"); } }
As you can see, delegate is almost the same as the event, which is different from the initialization problem.
Let's look at a set of code:
classProgram {Static voidMain (string[] args) {EventClass e=NewEventClass (); E.goevent+=E.gofun; E.goevent+=e.gofun2; Eventclass.go Go=NewEventclass.go (E.gofun); Go+=e.gofun2; //Execution//Error 1 Event "Eventclass.goevent" can only appear to the left of + = or-= (except when used from type "EventClass")E.goevent ("test2");//ErrorGo"test2");//SuccessConsole.WriteLine ("Done ."); Console.readkey (); } }
You can see the difference: The event can only be used outside the + = or-= operation.
/* * When the event keyword is available, the program will run normally. I removed the event and the program worked as normal.
* Event is simply a subset of delegates that restricts the ability to delegate instance objects. * For example: Events can only be performed +,- not directly func (...). And when I take out the event, I can use it directly. */
Take a look at the results of the anti-compilation:
You can see the diagram
The Go delegate still has a calling method
Event events only exist with the Add and remove methods
The event encapsulates a part of a behavior that should not otherwise be exposed by limiting delegate.
Delegate and event have to say the relationship ~