C # delegated application Summary

Source: Internet
Author: User
1. What is commissioned by the 1.1 Official explanation

A delegate is a type that defines the method signature. When instantiating a delegate, You can associate its instance with any method with a compatible signature. You can call a method by entrusting an instance.

1.2 understanding

A delegate is a class that executes methods (functions.

An event is a special delegate.

Ii. How to delegate 2.1 delegate

Public Delegate int testdelegate (int x, int y );

2.2 Action

Action is a generic delegate without return values.

Action indicates a delegate with no parameter and no return value.

Action <int, string> indicates that the input parameter int exists, and the string value does not return a delegate.

2.3 func

Func is a generic delegate with a returned value.

Func <int> indicates that there is no parameter, and the return value is the delegate of Int.

Func <object, String, int> indicates that the input parameter is an object, and the string return value is an int delegate.

2.4 Predicate

Predicate is a generic delegate that returns the bool type.

Predicate <int> indicates that the input parameter is int and the bool delegate is returned.

Differences between 2.5 and 4

Delegate has at least 0 parameters and up to 32 parameters. You can specify no return value or the return value type.

The action must have at least one parameter, at most four parameters, and no return value,

Func must have at least 0 parameters and at most 4 parameters, which are returned Based on the return value of the generic type. There must be a return value, not void

Predicate has at least one parameter and at most one parameter. The return value is fixed to bool.

Iii. How to Use delegate 3.1 labmda expressions

Testdelegate D2 = (string name) => {console. writeline ("Hello, {0 }! ", Name );};

D2 ("Terry ");

3.2 anonymous method

Delegate void testdelegate (string myname );

Testdelegate D2 = delegate (string name)
{

Console. writeline ("Hello, {0 }! ", Name );

};

D2 ("test ");

3.3 function declaration

Private void delegatemethod (string name)

{

Console. writeline ("Hello, {0 }! ", Name );

}

Testdelegate D2 = new testdelegate (delegatemethod );

D2 ("test ");

Iv. Features of delegated use

Delegation is similar to C ++ function pointers, but they are type-safe.

The delegate allows passing methods as parameters.

A delegate can be used to define a callback method.

The delegate can be linked together. For example, multiple methods can be called for an event.

The method does not have to match the delegate signature completely.

V. Delegated Use Cases

Delegation is generally used in observer mode (Observer mode ).

The observer design mode is used to define a one-to-many dependency between objects, so that when the state of an object changes, other objects dependent on it will be automatically notified and updated.

The observer mode mainly includes the following two types of objects:

Monitored object: usually contains the content that other objects are interested in.

Monitored by: When something in an object occurs, the builder is notified, and the builder takes corresponding actions.

For example, when your program processes a large volume of data, you need to display a progress bar on the program interface for friendly prompts. At this time, you can delegate to achieve quite convenient.

Example:

Public Delegate void delegatemethod (INT position, int maxvalue );

  public class TestDelegate
    {
        public DelegateMethod OnDelegate;

Public void dodelegatemethod ()
{
Int maxvalue = 100;
For (INT I = 0; I <maxvalue; I ++)
{
If (this. ondelegate! = NULL)
{
This. ondelegate (I, maxvalue );
}
}
}

}

TestDelegate test = new TestDelegate();
            this.textBox1.Text = "";
            this.progressBar1.Value = 0;
            test.OnDelegate = new DelegateMethod(delegate(int i, int maxValue)
            {
                this.textBox1.Text += i.ToString() + Environment.NewLine;
                this.progressBar1.Maximum = maxValue;
                this.progressBar1.Value++;
            });
            test.DoDelegateMethod();
6. How to clear delegation

1. Declare the delegate method in the class and remove the delegate reference cyclically.

The method is as follows:

Public class testdelegate
{
Public delegatemethod ondelegate;

                 public void ClearDelegate()
        {
            while (this.OnDelegate != null)
            {
                this.OnDelegate -= this.OnDelegate;
            }
        }
    }
2. If the method for clearing the delegate is not stated in the class, we can use getinvocationlist to query the delegate reference and then remove it.

The method is as follows:

Testdelegate test = new testdelegate ();

If (test. ondelegate! = NULL)
{
System. Delegate [] dels = test. ondelegate. getinvocationlist ();
For (INT I = 0; I <dels. length; I ++)
{
Test. ondelegate-= dels [I] As delegatemethod;
}
}

VII. Practical Examples

Function Requirement: query the amount of toner for the printer. If the value is less than 50, an email is sent to the customer for a reminder.

Code before optimization

Namespace delegateexample. Before
{
Public class spyprintertoner
{
Public void checkprintertonerislower ()
{
Physicalprinteraction action = new physicalprinteraction ();
Int remaintoner = action. selectprintertoner ();
If (remaintoner <50)
{
Messagecontroller controller = new messagecontroller ();
Controller. sendmessage ("Printer name ");
}
}
}
 
Public class messagecontroller
{
Public void sendmessage (string printername)
{
// Todo: sendmessage
}
}
 
Public class physicalprinteraction
{
Public int selectprintertoner ()
{
Return 80;
}
}
}

Call:

Delegateexample. Before. spyprintertoner toner = new before. spyprintertoner ();
Toner. checkprintertonerislower ();

The above code can also be said to adopt object-oriented programming, but there is an unnecessary coupling between spyprintertoner and messagecontroller, resulting in the workload of program maintenance in the future and the inconvenience of program expansion.

How can we reduce the coupling between spyprintertoner and messagecontroller to achieve the goal of High Cohesion and low coupling.

Obviously, we can use the observer mode.

Optimized Code

Namespace delegateexample. After
{
 
 
Public class spyprintertoner
{
Public action <string> onsendmessage;
 
Public void checkprintertonerislower ()
{
Physicalprinteraction action = new physicalprinteraction ();
Int remaintoner = action. selectprintertoner ();
If (remaintoner <50)
{
If (this. onsendmessage! = NULL)
{
This. onsendmessage ("Printer name ");
}
}
}
}
 
Public class messagecontroller
{
Public void sendmessage (string printername)
{
// Todo: sendmessage
}
}
 
Public class physicalprinteraction
{
Public int selectprintertoner ()
{
Return 80;
}
}
}

Call

Delegateexample. After. spyprintertoner toner = new after. spyprintertoner ();
Toner. onsendmessage + = new action <string> (New after. messagecontroller (). sendmessage );
Toner. checkprintertonerislower ();

After such optimization, the coupling between the two classes is reduced.

If you need to add im-type messages or other types of messages after the change, you only need to add another delegate, then, the spyprintertoner class is coupled with the IM processing class or other classes.

8. Use func to delegate code optimization

Similar code is often seen during project development:

Try
{
Do ();
}
Catch (exception ex)
{
Logexception (Ex );
}
Finally
{
Dofinally ();
}

This can cause code redundancy and cause a lot of inconvenience to code maintenance in the future.

There are many methods to implement, such as AOP and delegation. Here we will focus on how to use the func delegate to achieve code optimization.

 
Private void callmethod (func <string> func)
{
Try
{
Func ();
}
Catch (exception ex)
{
Logexception (Ex );
}
Finally
{
Dofinally ();
}
}

Callmethod (New func <string> (DO ));

We pass the method as a delegate, which saves a lot of redundant code.

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.