C # delegated Learning (1)

Source: Internet
Author: User

I want to share with you how to use C # delegation today:

A delegate is a data structure that references static methods, class instances, and class instance methods. Let's take a look at the following example:

Int I = 100; // defines the number of integers.

Public Delegate string getstring (); // defines a delegate getstring, which returns the string type.

Getstring firstmethod = new getstring (I. tostring); // a delegate whose instantiation type is getstring.

Let's not talk about it. Let's look at an example. It's a simple example that everyone can understand:

View code
 Using  System;
Using System. Collections. Generic;
Using System. text;

Namespace Wrox. procsharp. Delegates
{
Class Mathoperations
{
Public Static Double Multiplybytwo ( Double Value)
{
Return Value * 2 ;
}

Public Static Double Square ( Double Value)
{
Return Value * Value;
}
}


Delegate Double Doubleop ( Double X );

Class Mainentrypoint
{
Static Void Main ()
{
Doubleop [] operations =
{
Mathoperations. multiplybytwo,
Mathoperations. Square
// New doubleop (mathoperations. multiplybytwo ),
// New doubleop (mathoperations. Square)
};

For ( Int I = 0 ; I < Operations. length; I ++ )
{
Console. writeline ( " Using operations [{0}]: " , I );
Processanddisplaynumber (Operations [I], 2.0 );
Processanddisplaynumber (Operations [I], 7.94 );
Processanddisplaynumber (Operations [I], 1.414 );
Console. writeline ();
}
Console. Readline ();
}

Static Void Processanddisplaynumber (doubleop action, Double Value)
{
Double Result = Action (value );
Console. writeline (
" Value is {0}, result of operation is {1} " , Value, result );
}
}
}

A good way to understand the delegate is to treat the delegate as a name for the method signature and return type.

Processanddisplaynumber (Operations [I], 2.0); // indicates passing the delegate to the processanddisplaynumber () method.

I will write it here today. For more information about the many shortcomings, please consult.

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.