C # 2.0 Learning - Anonymous Agent

xiaoxiao2021-04-08  441

Compilation and execution:

CSC AnonymousDelegates.cs

AnonymousDelegates

AnonymousDelegates.cs: // copyright (c) Microsoft Corporation. All Rights Reserved.

Using system.collections.generic; use system.text;

Namespace AnonymousDelegate_sample {

// define the delegate method. Delegate Decimal Calculatebonus (Decimal Sales);

// define an Employee Type. Class Employee {Public String Name; Public Decimal Sales; Public DeciMal Bonus; Public Calculatebonus Calculation_Algorithm;

Class program {

// this class will define Two delegates That Perform a Calculation. // The first Will be a named method, The second anonymous delegate.

// this is the named method. // IT defines One Possible Implementation of the Bonus Calculation Algorithm.

Static Decimal CalculateStandardbonus (Decimal Sales) {Return Sales / 10;

Static void main (string [] args) {

// a value used in the calculation of the bonus. // Note: This Local Variable Will Become A "Captured Outer Variable". Decimal Multiplier = 2;

// this delegate is defined as a named method. Calculatebonus standard_bonus = new calculatebonus (Calculatestandardbonus);

// this delegate is anonymous - there is no named method. // it defines an alternative bonus calculation algorithm. Calculatebonus enhanced_bonus = delegate (DECIMAL SALES) {Return Multiplier * Sales / 10;}

// Declare Some Employee Objects. Employee [] Staff = New Employee [5];

// Populate the array of employees. For (INT i = 0; i <5; i ) staff [i] = new Employee ();

// Assign Initial Values ​​to Employees. Staff [0] .name = "mr Apple"; Staff [0] .sales = 100; Staff [0] .calculation_algorithm = standard_bonus; staff [1] .name = "ms banana"; Staff [1] .sales = 200; Staff [1] .calculation_algorithm = standard_bonus;

Staff [2] .Name = "mr Cherry"; Staff [2] .sales = 300; Staff [2] .calculation_algorithm = standard_bonus;

Staff [3] .Name = "mr Date"; staff [3] .sales = 100; staff [3] .calculation_algorithm = enhanced_bonus;

Staff [4] .name = "ms elderberry"; staff [4] .sales = 250; staff [4] .calculation_algorithm = enhanced_bonus;

// Calculate Bonus for All Employees foreach (Employee Person in Staff) Performbonuscalculation (Person);

// Display The Details of All Employees Foreach (Employee Person in Staff) DisplayPersondetails (Person);

}

Public Static Void PerformBonuscalculation (Employee Person) {

// This method uses the delegate stored in the person object // to perform the calculation // Note:. This method knows about the multiplier local variable, even though // that variable is outside the scope of this method // The multipler. Varaible is a "capture outr variable". Person.bonus = person.calculation_algorithm (Person.sales);}

Public Static Void DisplayPersondetails (Employee Person) {Console.writeline (persou.writeline); console.writeline ("-------------"); }}}

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

New Post(0)