A brief analysis of trust in C #

Source: Internet
Author: User

The trust is the addressing method. NET version number. In C + +. A function pointer is simply a pointer to a memory location, which is not type-safe. whereas. NET trusts are completely different, a delegate is a class of security type that defines the type of return and the number of parameters.
When passing methods to other methods, the use of trust is required.

When a class is used in C #, it is divided into two phases.

You first need to define this class, which tells the compiler what the class is made of. Then, instantiate an object (unless only static methods are used).

For the trust is similar, also need two steps.

You must first define the trust you want to use. You must then create one or more instances of the commit.

Definition syntax:

delegatevoid IntMethodInoker(int x);delegatedouble TwoLongsOp(longlong second);delegatestring GetString();

Defining a commit is basically defining a new class. So it is possible to define the entrusted in the same place as the definition class. That is, the ability to define an internal definition within a class that can be defined as a top-level object in a namespace, regardless of the external definition of the class.

Depending on the visibility of the trust definition, and the scope of the trust, it is possible to apply random access modifiers to the definition of the trust: public, private, protected, etc.
Like what:

publicdelegatestringGetAString();

Use entrusted:

privatedelegatestringGetAString();staticvoid Main(){    int x=40;    new GetAString(x.ToString);    Console.WriteLine("String is {0}",firstStringMethod () );}

Can be seen by the above code. C # 's commit is always syntactically accepting a parameter constructor. This parameter is the method of entrusting the reference, but this method must match the signature at the time of the initial definition of the commit.

As a matter of fact. The same applies to the invocation () method, which provides parentheses to the entrusted instance and invokes the entrusted class.

Use invoke to complete marshaling of a commit method. Similar to using the SendMessage method to send a message to an interface thread is a synchronous method. That is, the Invoke method does not return until the method of the Invoke Marshal is finished, and the caller thread is blocked.

Because Firststringmethod is a variable of a commit type, the C # compiler replaces Firststringmethod () with Firststringmethod.invoke ().

firstStringMethod();firstStringMethod.Invoke();

To reduce the amount of input. Simply by entrusting an instance, you can simply pass the name of the address, that is, entrust judgment .

GetAString firstStringMethod = new GetAString(x.ToString);GetAString firstStringMethod = x.ToString;

Note : The input does not act as x. ToString (). Nor can it be passed to the entrusted variable. X.tostring means assigning the address of the method to the commit variable.

Multicast Trust:
A trust can include multiple methods, such as a multicast trust. Assume that multicast trusts are called. Multiple methods can be called consecutively sequentially. However, the entrusted signature must return void. Otherwise, only the result of the last method entrusted to the invocation can be obtained.


Multicast Trust Demo Sample routines:

Delegate voidDelegate_multicast (intXinty); Class class2{Static voidMETHOD1 (intXintY) {Console.WriteLine ("You r in Method 1"); }Static voidMETHOD2 (intXintY) {Console.WriteLine ("You r in Method 2"); } Public Static void Main() {Delegate_multicast func =NewDelegate_multicast (METHOD1); Func + =NewDelegate_multicast (METHOD2); Func1,2);//Method1 and METHOD2 are calledFunc-=NewDelegate_multicast (METHOD1); Func2,3);//Only Method2 is called}}

Analytical:
The above Demo sample program defines two accepted integer parameters named Method1 and Method2, and a method with a return type of void.
In the main function, create the entrusted object using the following declaration:
Delegate_multicast func = new Delegate_multicast (METHOD1);
Then use + = To add the trust, use-= to remove the trust.

merger entrusted:
One purpose of the entrusted object is to be able to use the + operator to assign them to a trusted instance to be trusted for multicast.

The trust of a combination invokes the two entrusted to make it.

Only the same type of entrusted talent is enough to combine.
- The operator can be used to remove a component from a combined consignment.

Delegate voidDel (string s);classtestclass{Static voidHello (string s) {System.Console.WriteLine ("Hello, {0}!", s); }Static voidGoodbye (string s) {System.Console.WriteLine ("Goodbye, {0}!", s); }Static voidMain () {Del A, B, C, D;//Create The delegate object A that references        //The method Hello:A = Hello;//Create The delegate object B that references        //The method Goodbye:b = Goodbye;//The delegates, A and B, is composed to form C:c = a + B;//Remove A from the composed delegate, leaving D,        //Which calls only the method Goodbye:D = c-a; System.Console.WriteLine ("Invoking delegate A:"); A"A"); System.Console.WriteLine ("invoking delegate B:"); b"B"); System.Console.WriteLine ("Invoking delegate C:"); C"C"); System.Console.WriteLine ("Invoking delegate D:"); D"D"); }}/*-------------------------Output invokingDelegateA:hello, A! InvokingDelegateB:goodbye, B! InvokingDelegateC:hello, C! Goodbye, C! InvokingDelegateD:goodbye, D! ----------------------*/

anonymous method:
Until now. If you want to use entrusted work. Method must already exist. But there is also a way to use trust: through anonymous methods.

An anonymous method is a piece of code that is used as a delegate's number of references.
The syntax for defining a commit with an anonymous method is no different from the previous definition.

But there's a difference when it comes to instantiation.


Assume that anonymous methods are used. You do not have to create a separate method, thus reducing the coding overhead required to instantiate the commit.

Like what. Assuming that the overhead required to create a method is unnecessary, it is useful to specify a block of code in the place where you entrust it. Starting a new thread is a good example of a demo. Instead of creating many other methods for entrusting, the thread class can create a thread and include code that the thread is running.

void StartThread(){    System.Threading.Thread t1 = new System.Threading.Thread      (delegate()            {                System.Console.Write("Hello, ");                System.Console.WriteLine("World!");            });    t1.Start();}

The commit type derives from the Delegate class in the. NET Framework.

The commit types are encapsulated, they cannot derive from other classes, and they cannot derive their own definition classes from Delegate. Because the instantiation of the entrusted is an object. So it can be passed or assigned as a parameter to a property. This agrees that the method is accepted as a participant and is later invoked.

This is called an asynchronous callback and is a frequent usage of notifying callers when a long process is complete. When the trust is used in such a way. There is no need to know the implementation method to use with the entrusted code. Functionality is similar to the functionality provided by the encapsulated interface.

A brief analysis of trust in C #

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.