Page d'Accueil

Rangées et délégués

 

Introduction

Pour affiner plus tard l'appel à un groupe de méthodes qui exécute le même genre de tâche, vous pouvez déclarer une rangée de délégués. D'abord, créez le délégué nécessaire. Voici un exemple:

using System;

delegate double Measure(double R);

public static class Program
{
    static int Main(string[] args)
    {
        return 0;
    }
}

Avant de créer la rangée, vous devez d'abord avoir les méthodes auxquelles vous vous référeriez. Ces méthodes doivent avoir une signature semblable. Ceci signifie qu'elles doivent retourner le même type de valeur, elles doivent avoir le même nombre d'arguments et elles doivent avoir le(s) même(s) type(s) d'argument(s) éventuellement. Voici les exemples de telles fonctions

:

using System;

delegate double Measure(double R);

public class Circle
{
    const double PI = 3.14159;

    double Diameter(double Radius)
    {
        return Radius * 2;
    }

    double Circumference(double Radius)
    {
        return Diameter(Radius) * PI;
    }

    double Area(double Radius)
    {
        return Radius * Radius * PI;
    }
}

public static class Program
{
    static int Main()
    {
        return 0;
    }
}

Une rangée de délégués

Pour créer une rangée de délégués, déclarez une rangée normale comme nous avons fait jusqu'ici. Vous pouvez initialiser chaque membre en utilisant son index et en appelant la méthode correspondante. Ceci peut être fait comme suit :

using System;

delegate double Measure(double R);

public class Circle
{
    const double PI = 3.14159;

    public double Diameter(double Radius)
    {
        return Radius * 2;
    }

    public double Circumference(double Radius)
    {
        return Diameter(Radius) * PI;
    }

    public double Area(double Radius)
    {
        return Radius * Radius * PI;
    }
}

public static class Program
{
    static int Main()
    {
        double R = 12.55;
        Circle circ = new Circle();
        Measure[] Calc = new Measure[3];

        Calc[0] = new Measure(circ.Diameter);
        double D = Calc[0](R);
        Calc[1] = new Measure(circ.Circumference);
        double C = Calc[1](R);
        Calc[2] = new Measure(circ.Area);
        double A = Calc[2](R);

        Console.WriteLine("Circle Characteristics");
        Console.WriteLine("Diameter:      {0}", D);
        Console.WriteLine("Circumference: {0}", C);
        Console.WriteLine("Area:          {0}\n", A);

        return 0;
    }
}

Ceci produirait :

Circle Characteristics
Diameter:      25.1
Circumference: 78.8539
Area:          494.808

Étude pratique Étude pratique : Utiliser une rangée de délégués

  1. Commencez Microsoft Visual C# Express Edition et créez une nouvelle application de console appelée MultipleChoiceQuestion1
  2. Changez le fichier Program.cs comme suit:
     
    using System;
    
    namespace MultipleChoiceQuestion1
    {
        public class Program
        {
            enum TMCQuestion { One, Two, Three, Four, Five };
            delegate char Question();
    
            static char Sequence()
            {
                char Answer;
    
                Console.WriteLine("Which sequence of numbers does not appear ");
                Console.WriteLine("to follow a recognizable order?");
                Console.WriteLine("(a)   3   9  27  33");
                Console.WriteLine("(b)   3   6   9  12");
                Console.WriteLine("(c)   2   4   6   8");
                Console.WriteLine("(d) 102 204 408 816");
                Console.Write("Your Answer? ");
                Answer = char.Parse(Console.ReadLine());
    
                return Answer;
            }
    
            static char Expression()
            {
                char Response;
    
    Console.WriteLine("Select the best expression to complete the empty space");
    Console.WriteLine("When ... drugs to a business address, traffickers often ");
                Console.WriteLine("omit a recipient name");
                Console.WriteLine("(a) to send");
                Console.WriteLine("(b) senders");
                Console.WriteLine("(c) sending");
                Console.WriteLine("(d) dealing");
                Console.Write("Your Answer? ");
                Response = char.Parse(Console.ReadLine());
    
                return Response;
            }
    
            static char Sentence()
            {
                char Answer;
    
    Console.WriteLine("Even ... there are 76,000 lawyers in that city, ");
                Console.WriteLine("it is still a small community");
                Console.WriteLine("(a) although");
                Console.WriteLine("(b) though");
                Console.WriteLine("(c) for");
                Console.WriteLine("(d) since");
                Console.Write("Your Answer? ");
                Answer = char.Parse(Console.ReadLine());
    
                return Answer;
            }
    
            static char WrongWord()
            {
                char Wrong;
    
                Console.WriteLine("Select the wrong word that would complete ");
                Console.WriteLine("the sentence");
    Console.WriteLine("For this type of business, revenue gains are ...");
                Console.WriteLine("(a) limited");
                Console.WriteLine("(b) scarce");
                Console.WriteLine("(c) limitless");
                Console.WriteLine("(d) claiming");
                Console.Write("Your Answer? ");
                Wrong = char.Parse(Console.ReadLine());
    
                return Wrong;
            }
    
            static char Right()
            {
                char Sentence;
    
                Console.WriteLine("Select the right sentence");
    Console.WriteLine("(a) The company is expecting to reducing inventory,");
    Console.WriteLine("    control cost, and efficiency improvement.");
    Console.WriteLine("(b) The company expects to reduce inventory,");
    Console.WriteLine("    control cost, and improve efficiency.");
    Console.WriteLine("(c) The company expects to reduce inventory,");
    Console.WriteLine("    control cost, and improving efficiency.");
    Console.WriteLine("(d) The company is expecting to reducing inventory,");
    Console.WriteLine("    controlling cost, and efficiency improvement.");
                Console.Write("Your Answer? ");
                Sentence = char.Parse(Console.ReadLine());
    
                return Sentence;
            }
    
            static int Main()
            {
                const int NumberOfQuestions = 5;
                char[] Answer = new char[NumberOfQuestions];
    
                Question[] MCQ = new Question[NumberOfQuestions];
    
                MCQ[0] = new Question(Sequence);
                MCQ[1] = new Question(Expression);
                MCQ[2] = new Question(Sentence);
                MCQ[3] = new Question(WrongWord);
                MCQ[4] = new Question(Right);
    
                for (int i = 0; i < NumberOfQuestions; i++)
                {
                    Console.WriteLine("Question {0}", i + 1);
                    Answer[i] = MCQ[i]();
                    ValidateAnswer(i + 1, Answer[i]);
                    Console.WriteLine();
                }
    
                return 0;
            }
    
            static void ValidateAnswer(int QstNbr, char Ans)
            {
                switch (QstNbr)
                {
                    case 1:
                        if (Ans == 'a' || Ans == 'A')
                            Console.WriteLine("Right Answer");
                        else
                        {
           Console.WriteLine("Wrong Answer - The right answer was 'a'");
           Console.WriteLine("(a) Starting at 3, 3*3=9 and 3*9=27");
           Console.WriteLine("    There is no obvious way to determine 33");
                        }
                        break;
    
                    case 2:
                        if (Ans == 'c' || Ans == 'C')
                            Console.WriteLine("Right answer");
                        else
           Console.WriteLine("Wrong Answer - The right answer was 'c'");
                        break;
    
                    case 3:
                        if (Ans == 'b' || Ans == 'B')
                            Console.WriteLine("Right answer");
                        else
           Console.WriteLine("Wrong Answer - The right answer was 'b'");
                        break;
    
                    case 4:
                        if (Ans == 'd' || Ans == 'D')
                            Console.WriteLine("Right answer");
                        else
           Console.WriteLine("Wrong Answer - The right answer was 'd'");
                        break;
    
                    case 5:
                        if (Ans == 'b' || Ans == 'B')
                            Console.WriteLine("Right answer");
                        else
           Console.WriteLine("Wrong Answer - The right answer was 'b'");
                        break;
    
                    default:
                        Console.WriteLine("Invalid Answer");
                        break;
                }
            }
        }
    }
  3. Exécutez l'application et l'examiner. Voici un exemple :
     
    Question 1
    Which sequence of numbers does not appear
    to follow a recognizable order?
    (a)   3   9  27  33
    (b)   3   6   9  12
    (c)   2   4   6   8
    (d) 102 204 408 816
    Your Answer? a
    Right Answer
    
    Question 2
    Select the best expression to complete the empty space
    When ... drugs to a business address, traffickers often
    omit a recipient name
    (a) to send
    (b) senders
    (c) sending
    (d) dealing
    Your Answer? d
    Wrong Answer - The right answer was 'c'
    Question 3
    
    Even ... there are 76,000 lawyers in that city,
    it is still a small community
    (a) although
    (b) though
    (c) for
    (d) since
    Your Answer? b
    Right answer
    Question 4
    
    Select the wrong word that would complete
    the sentence
    For this type of business, revenue gains are ...
    (a) limited
    (b) scarce
    (c) limitless
    (d) claiming
    Your Answer? d
    Right answer
    Question 5
    
    Select the right sentence
    (a) The company is expecting to reducing inventory,
        control cost, and efficiency improvement.
    (b) The company expects to reduce inventory,
        control cost, and improve efficiency.
    (c) The company expects to reduce inventory,
        control cost, and improving efficiency.
    (d) The company is expecting to reducing inventory,
        controlling cost, and efficiency improvement.
    Your Answer? a
    Wrong Answer - The right answer was 'b'
    
    Press any key to continue . . .
  4. Fermez la fenêtre DOS
 

Précédent Copyright © 2007, Yevol Suivant