Technical lectures:. Net delegation, events and applications, and discussion on Software Project Development

Source: Internet
Author: User
ArticleDirectory
    • 1.1. Net delegation Concept
    • 1.2. Net delegate statement and features
    • 1.3. Net Commission secrets
    • 1.4. Net delegated application description
    • 1.5. Net delegate Example 1: Transfer Method
    • 1.6. Net delegate Example 2: function callback
    • 2.1. Net event Concept
    • 2.2 five steps to design. Net events
    • 2.3 event Design Example
    • Step 1: Define the event parameter class
    • Step 2: declare the event handler delegate
    • Step 5 and Step 4: define class event members and motivate (publish) Events
    • Step 2: Subscribe to events
    • Summary and further study
    • 3.1 Development document
    • 3.2 Post-Maintenance
    • 3.3 Technical Accumulation

Address: http://blog.csdn.net/hulihui/archive/2008/09/30/3002873.aspx

This lecture covers three aspects:. Net delegation,. Net events, and software project development.

    • 2008 technical lecture program code and PPT
1. Net delegation and Application
1.1. Net delegation Concept

In Oop, objects with the same attributes are abstracted to become types (Class). Then, functions or methods with the same attributes (also known as functions with the same signature ):

    • Same return type
    • The parameter types, order, and number of parameters are the same.

What is the concept after abstraction? For example, the sum of the square after each number between 1 and N: int squaresum (int n) andCubeInt cubesum (int n), which has the same function Signature: int type, only one parameter, and INT type.

 
Static private int squaresum (int n)
{
Int m = 0;
For (int K = 1; k <= N; k ++)
{
M + = K * K;
}
Return m;
}
 
Static private int cubesum (int n)
{
Int m = 0;
For (int K = 1; k <= N; k ++)
{
M + = K * K;
}
Return m;
}

These function abstractions with the same attributes are a new type concept proposed by. Net-delegate, with the keyword delegate.

1.2. Net delegate statement and features

Similar to the function declaration of C/C ++/C #, the name of a delegate must include the delegate name, return type, parameter, and type. For example, declare the delegate powersum of the two previously defined functions as follows:

 
Public Delegate int powersum (int n );

In particular, a general class of event processing delegate eventhandler declares the following:

 
Public Delegate void eventhandler (Object sender, eventargs E)

Obviously, unlike the class definition, the delegate name does not need to define members. It only acts as a representation (delegate means ). In addition, delegate is also a class. Its base class is multicastdelegate, the upper class is delegate, and the top class is object.

1.3. Net Commission secrets

The title "secrets" refers to the original sentence of Jeffrey richeter's ". Framework Design (version 2nd) CLR via C. For example, the class hierarchy of the delegate powersum defined above, many methods and method parameters are omitted, and the diagram is not very standard (the begininvoke () parameter has ellipsis ).


We can see that:

    • The delegate contains a linked list, which can be the combine () and remove () instance methods.
    • The delegate chain provides an access interface for the delegate object
    • Delegation is the basis of asynchronous programming. begininvoke () and endinvoke () are two common asynchronous call functions.
1.4. Net delegated application description
    • Microsoft. NET Framework provides a function callback mechanism through delegation. -- Framework Design (version 2nd) CLR via C # Jeffrey richeter
    • Is a type-safe method reference, which can be considered as a type-safe C function pointer. --. NET Component Programming Juval Lowy
    • To send a method to another method, you need to delegate it. Unlike C function pointers,. Net delegation is type-safe. -- C # advanced programming Christian Nagel

From the descriptions of the famous books above, we can see that the main purposes of. Net delegation are three: 1) function callback; 2) transfer method; 3) event mechanism.

1.5. Net delegate Example 1: Transfer Method

There are two ways to pass a delegate as a method. First, directly transfer the method. This method is calledDelegate Inference; Second, it is passed after the delegate object is created, which is a conventional method. The preceding delegate is used to define a function for calling a method: int getpowersum (powersum PS) is as follows. This function is used to calculate the exponent from 1 to 10.

 
Static private int getpowersum (powersum PS)
{
Return PS (10 );
}

Call using delegated InferenceCodeAs follows:

 
Int P2 = getpowersum (squaresum );
Int P3 = getpowersum (cubesum );

The code for creating a delegate object is as follows:

 
Powersum PS2 = new powersum (squaresum );
Powersum PS3 = new powersum (cubesum );

P2 = PS2 (10 );
P3 = PS3 (10 );
1.6. Net delegate Example 2: function callback

One of the most common callback applications is the function called when the timer arrives. The involved types are as follows (. NET has three timer types, which are the timer in the thread namespace system. Threading ):

 
Public sealed timer (timercallback callback, object state, int duetime, int period );
Public Delegate void timecallback (Object State );
    • In the timer type, callback is an object that delegates timercallback; State is the State parameter during the call and can be flexibly applied; duetime is the waiting time for the timer to start timing; period is the timing cycle, call the method callback every cycle.
    • The delegate definition of the callback function calllback indicates that the callback function of the Timer class timer to the point cannot have a return type, but must have a parameter of the object type. Note that the so-called inverter entrusted here cannot be used

A point-to-point callback function is defined. The output string information is as follows:

 
Static private void timeclick (object state)
{
Console. writeline ("time click 500 ms ");
}

The timer application code for Ms reporting is as follows:

 
System. Threading. timercallback callback = new system. Threading. timercallback (timeclick );
System. Threading. Timer timer = new system. Threading. Timer (callback, null, 0,500 );

Since the callback function is relatively simple, anonymous delegation can be used. The Code is as follows:

System. Threading. timercallback callback = new system. Threading. timercallback
(
Delegate (object state)
{
Console. writeline ("time click 500 ms ");
}
);

System. Threading. Timer = new system. Threading. Timer (callback, null, 0,500 );
2. Net events and applications (back to top)
2.1. Net event Concept

How can an object receive notifications when an event occurs on another object? Common Methods in VB and C # are as follows:

    • VB button (command) Click Event: Sub commandementclick ()
    • C # button click event: void button#click (Object sender, eventargs E)

This indicates that an event is a signal mechanism that automatically sends a notification to an object when an activity occurs. It is an external message sending interface defined by the object. If other objects are interested in the event, an event is registered for the event.Program. When an event occurs, all the handlers registered with the event will be called.

The object for publishing an event is calledPublisher (publisher) or event SourceRelease events are also calledFire event. The object that follows the event is calledEvent receiver (sinker) or subscriber (subscriber)The subscription event is also called the registration event method. The publisher calls the subscriber registration method .. The. NET event model is built on the delegate mechanism and supports event definition, release, subscription, and removal.

2.2 five steps to design. Net events
    1. Define parameter type:Derive the required event parameter class from eventargs
    2. Define event handler delegate:Related to Step 1. This step is generally replaced by generic delegation.
    3. Define event members:In a custom class, the event handler delegates to define one or more event members.
    4. Event triggering:Notify all event subscribers in the event triggering method of the custom class
    5. Subscribe to events: Other Object Registration event handler

It should be noted that steps 3rd, 4, and 5 must exist, and steps 1st and 2 can be omitted as appropriate:

    • The
      Two steps can be saved. If the standard event handler delegate type is used: void eventhandler (Object sender, eventargs
      E), you only need to give the event parameters in step 1, and then use the generic delegate: eventhandler <t> to define the event members of the class. T indicates the event parameter type.
    • If you do not have custom event parameters, skip steps 1 and 2 and use eventhandler to define the event members of the class.
2.3 event Design Example
    • Compile a keyboard listener to count the number of buttonsTkeylisten
    • TkeylistenYou can publish the number of times that a listener has been hit and check the returned parameter values.
    • The object that registers the event can terminate the listening loop.
Step 1: Define the event parameter class
Public class keyeventargs: eventargs
{
Private int m_keycount;
Private bool m_stop = false;

Public keyeventargs (INT keycount) // specifies the key Count value when an event is published.
{
M_keycount = keycount;
}

Public int keycount
{
Get {return m_keycount ;}
}

Public bool stop
{
Get {return m_stop ;}
Set {m_stop = value;} // event subscriber can modify
}
}
Step 2: declare the event handler delegate
 
Public Delegate void keyeventhandler (Object sender, keyeventargs E );

In actual use, unless the preceding delegate has other purposes, it is generally replaced by the generic delegate eventhandler <t>, where T is the event parameter type.

Step 5 and Step 4: define class event members and motivate (publish) Events
Public class tkeylisten
{
// Public event keyeventhandler keypress; // Step 1: Define event members
Public event eventhandler <keyeventargs> keypress; // Step 1: generic delegation implementation

Public void listen ()
{
Console. writeline ("Please press key .");
Int keycount = 0;

While (true) // uses the loop listener to listen for the key action
{
Lelekeyinfo key = console. readkey ();
Keycount ++;

If (keypress! = NULL) // If a subscriber exists, that is, the delegated link is not empty.
{
Keyeventargs E = new keyeventargs (keycount );
Keypress (this, e); // Step 4: Activate the event and notify all subscribers

If (E. Stop) // determines the Event Response parameters
{
Break;
}
}
}
}
}

The above Code contains steps 1 and 4 of event implementation. Here, the loop Code while (true) contains the release (excitation) Event code, which is particularly described as follows:

    • You must determine whether the delegate chain (subscriber chain) is empty, that is, whether there is an event subscriber: If (keypress! = NULL ). If there is no event subscriber, directly publish the event keypress (this, E), the system will throw an exception "object reference is not set to the object instance"
    • When an event is fired or published, the first parameter is the object itself (this): keypress (this, E)
    • Keypress (this, e) actual execution process: traverses the event subscriber chain and executes each subscription event method, which has the same delegate type as keypress.
    • You can determine the Event Response parameter, that is, the subscriber can modify the parameter E. Stop. The publisher checks this parameter. If there are multiple subscribers, the above Code obtains only the parameters specified by the processing method of the last subscription event. To determine the parameters of each subscription method, you must use the delegate getinvocationlist () method to obtain the return parameters one by one.
Step 2: Subscribe to events
 
Static void main (string [] ARGs)
{
Tkeylisten demo = new tkeylisten ();
Demo. keypress + = countkey; // subscribe to events and use the delegate Inference Method
Demo. Listen ();
}

Static void countkey (Object sender, keyeventargs e) // event handling method
{
Console. writeline ("Press count:" + E. keycount );
If (E. keycount = 5) E. Stop = true; // stop after 5 times
}

Note: In the above Code, the event processing method countkey must be consistent with the event handler delegate or generic delegate. Note the following:

    • The subscribe event operator is: + =, And the remove subscribe operation is-=
    • Subscribe to a delegated object: Demo. keypress + = new keyeventhandler (countkey );
    • You can subscribe multiple times to generate the event chain: Demo. keypress + = delegate (){...}
Summary and further study

The main purposes of delegation are method calls, function callback, and events, and events are mainly used for sending messages out of the channel. For further study, consider the following:

    • Multicastdelegate)
    • Delegated change and Inverter
    • Delegate and asynchronous (programming) calls
    • Delegate or delegate link Exception Handling
    • Event accessors
    • Distributed events and asynchronous events
    • Event or event chain Exception Handling
3 Introduction to software project development (back to top) 3.1 Development document

Even for small software projects, at least the following development documents must be included:

    • Technical documents: requirement analysis, system running environment, system running configuration, database table design,AlgorithmDescription
    • Test Documents: Unit/integration test and Acceptance Test
3.2 Post-Maintenance
    • Long-term maintenance preparation: the maintenance period is generally reflected in the contract, generally 3 ~ 5 years
    • Code and document maintenance: Add maintenance documents to record all maintenance information
3.3 Technical Accumulation
    • Technical focus: Tools and languages, B/S and C/S models
    • Latest Technology: for example, air and Silverlight in RIA
    • Industry Knowledge: professional knowledge in the application field

The above mainly involves software projects with a minimum of three individuals, and does not involve large-scale project development methods that run in companies.

    • 2008 technical lecture program code and PPT

Address: http://blog.csdn.net/hulihui/archive/2008/09/30/3002873.aspx

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.