zoukankan      html  css  js  c++  java
  • C# 5 in a Nutshell

    1. What is delegate in C#?

    A delegate is an object that knows how to call a method.
    A delegate type defines the kind of method that delegate instances can call. Specifically,
    it defines the method’s return type and its parameter types.

    The followingdefines a delegate type called Transformer:
    delegate int Transformer (int x);

     Transformer is compatible with any method with an int return type and a single
    int parameter, such as this:
    static int Square (int x) { return x * x; }
    Assigning a method to a delegate variable creates a delegate instance:
    Transformer t = Square;

    complete code:

    public delegate int Transformer (int x);
    class Util
    {
        public static void Transform (int[] values, Transformer t)
        {
            for (int i = 0; i < values.Length; i++)
            values[i] = t (values[i]);
        }
    }
    
    class Test
    {
        static void Main()
        {
            int[] values = { 1, 2, 3 };
            Util.Transform (values, Square); // Hook in the Square method
            foreach (int i in values)
            Console.Write (i + " "); // 1 4 9
        }
        static int Square (int x) { return x * x; }
    }
  • 相关阅读:
    第四次上机练习
    第五周上机练习
    第四周作业
    第二次上机练习
    第三周作业
    第一次上机练习
    第一次作业
    第五周上级作业
    第一次上机0.0
    java第六周作业
  • 原文地址:https://www.cnblogs.com/davidgu/p/4276540.html
Copyright © 2011-2022 走看看