Entrusted in C #

xiaoxiao2021-03-06  51

Entrusted in C #

Introduction: The entrustment in C # is confused (I am an initiator), in different C # books, translated as a proxy, delegate, etc. .

The commissioned in C # is similar to a function pointer in C or C , but there is an essential difference: C or C is not type security, but the delegate in C # is object-oriented, and it is safe.

From a technical point of view, the delegate is a reference type to encapsulate methods with specific signatures and return types.

1, statement commission

C # Use the keyword delegate to declare the delegate type:

[Access Decoration] DELEGATE results Type Entrusted Identifier ([Distrametric List]);

The delegate type can be declared anywhere in the declaration class.

2, instantiate entrustment

Entrusting the NEW operator to instantiate.

The object referenced by the newly created entrusted instance is one of the following:

(1) Delegate to create a static method referenced in expressions

(2) Entrusting the target object referenced in the expression (this object cannot be null) and an instance method

(3) another commission

E.g:

Delegate Void MyDelegate (INT X);

Class myclass

{

Public Static Void Method1 (INT I)

{

}

Public void method2 (INT i)

{

}

}

Class testclass

{

Static void

Main

()

{

// static method

MyDelegate delegate1 = new mydlegate (myclass.method1);

// instance method

TestClass class1 = new myclass ();

MyDelegate delegate2 = new mydlegate (myclass.method2);

// Another commission

MyDelegate delegate3 = new mydelegate (delegate2);

}

}

3, use commission

The entrusted object is called by the name of the delegate object and the parameters to be passed to the parentheses. When calling a delegate, the primary form of calling expressions must be the value of the entrusted type.

Look at an example:

Namespace delegateTestSt

{

Public Delegate Int MyDelegateTest (INT I, INT J);

Class Calculate

{

Public Static Int Add (Int i, Int J)

{

Return I J;

}

Public Static Int Minus (INT I, INT J)

{

Return I-J;

}

}

Class delegateApp

{

Static void

Main

(String [] ARGS)

{

MyDelegateTest D0 = New MyDelegateTest (Calculate.add); // Declare an instance D0 of a MyDelegateTest, and initializes it with Calculate.ADD, which is actually linking the commission and method.

INT i = D0 (99, 1); // Start calling delegate, just like using static member methods Calculate.Add (INT I, INT J).

System.console.writeline ("This is the result of running: {0}", i);

MyDelegateTest D1 = New MyDelegateTest (Calculate.minus);

INT J = D1 (100, 99);

System.console.writeline ("This is the result of running minus: {0}", J);

System.console.readline ();

}

}

}

转载请注明原文地址:https://www.9cbs.com/read-117127.html

New Post(0)