现在的位置: 首页 > 综合 > 正文

[读书笔记]委托续

2012年08月12日 ⁄ 综合 ⁄ 共 6269字 ⁄ 字号 评论关闭

The C and C++ languages have long used the concept of function pointer. This was even more useful when programming for the Microsoft Windows operating systems because the Win32 library relies on the concept of callback functions. Callback functions are used in Microsoft Windows programming to process messages. For this reason and because of their functionality, callback functions were carried out in the .NET Framework but they were defined with the name of delegate.

回调是通过委托来定义的。

A delegate is a special type of user-defined variable that is declared globally, like a class. A delegate provides a template for a method, like an interface provides a template for a class. Like an interface, a delegate is not defined. Its role is to show what a useful method would look like. To support this concept, a delegate can provide all the necessary information that would be used on a method. This includes a return type, no argument or one or more arguments.

 

委托为方法提供一个模板,就像接口为类提供模板一样。和接口一样,委托是不需要定义的。它的作用就是展示一个方法应该是什么样子的。为了支持这样的观念,委托可以提供所有在方法里必须用到的信息。这包括返回值类型,有无参数或者多个参数。

 

一个普通示例:好像和委托没啥关系哈。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// In the above program, the clerk was asked to provide the number of months for the period of the loan. 
//Depending on the loan, one customer may want to specify the number of days necessary to pay the loan. 
//Another customer may want to pay a loan over a number of years. 
//To make this possible, we will allow the clerk to select the type of period for a loan.

namespace WattsALoan1
{
    class Program
    {
        static int Main(string[] args)
        {
            int Periods = 0;
            int TypeOfPeriod = 0;

            string PeriodName = null;
           
            double Principal, IntRate;
            LoanEvaluation loan = new LoanEvaluation();

            Console.WriteLine(
                "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
            Console.WriteLine("Loan Processing\n");
            Console.WriteLine(
            "This program allows you to calculate the amount of money a ");
            Console.WriteLine(
            "customer will owe at the end of the lifetime of a loan\n");

            Principal = loan.GetPrincipal();
            IntRate = loan.GetInterestRate();            

            loan.GetPeriod(ref TypeOfPeriod, ref Periods);
            
            if (TypeOfPeriod == 0)
            {
                // Since the user made a bad selection, stop the program here
                return 0;
            }// Since this "if" condition has a "return 0" line, if the "if"
            // condition produces true, the "return 0" means the function
            // would be terminated. If the condition is false, the inside of
            // this "if" condition would not execute and the function would
            // continue. This means that, if the condition is false, then
            // the "else' is implied. Therefore, we don't have to write an
            // "else" condition: it is automatic.

            if (TypeOfPeriod == 1)
            {
                PeriodName = "days";
            }
            else if (TypeOfPeriod == 2)
            {
                PeriodName = "months";
            }
            else if (TypeOfPeriod == 3)
            {
                PeriodName = "years";
            }


            Console.WriteLine(
                "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n");

            Console.WriteLine("==================================");
            Console.WriteLine("Loan Estimation");
            Console.WriteLine("----------------------------------");
            Console.WriteLine("Principal: {0:C}", Principal);
            Console.WriteLine("Interest:  {0:P}", IntRate / 100);
            Console.WriteLine("Period:    {0} {1}", Periods, PeriodName);
            Console.WriteLine("==================================\n");

            Console.ReadLine();

            return 0;

        }
    }
}

 

下面的是其中的LoanEvaluation类的代码:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WattsALoan1
{
    class LoanEvaluation
    {
        public double GetPrincipal()
        {
            Console.Write("Enter the Principal:         $");
            double P = double.Parse(Console.ReadLine());

            return P;
        }

        public double GetInterestRate()
        {
            Console.Write("Enter the Interest Rate (%): ");
            double r = double.Parse(Console.ReadLine());

            return r;
        }

        public int GetPeriod()
        {
            Console.Write("Enter the number of months:  ");
            int t = int.Parse(Console.ReadLine());

            return t;
        }

        public void GetPeriod(ref int TypeOfPeriod, ref int Periods)
        {
            Console.WriteLine("How do you want to enter the length of time?");
            Console.WriteLine("1 - In Days");
            Console.WriteLine("2 - In Months");
            Console.WriteLine("3 - In Years");
            Console.Write("Your Choice: ");
            
            TypeOfPeriod = int.Parse(Console.ReadLine());

            if (TypeOfPeriod == 1)
            {
                Console.Write("Enter the number of days: ");
                Periods = int.Parse(Console.ReadLine());
            }
            else if (TypeOfPeriod == 2)
            {
                Console.Write("Enter the number of months: ");
                Periods = int.Parse(Console.ReadLine());
            }
            else if (TypeOfPeriod == 3)
            {
                Console.Write("Enter the number of years: ");
                Periods = int.Parse(Console.ReadLine());
            }
            else
            {
                TypeOfPeriod = 0;
                // The user made an invalid selection. So, we will give up
                Console.WriteLine("Bad Selection\n");
            }
        }

    }
}

 

下面才是关于委托一个最简单的例子:

 

定义一个委托:

using System;

public delegate void Simple();

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

After declaring a delegate, it only provides a template for a method, not an actual method. In order to use it, you must define a method that would carry an assignment to perform. That method must have the same return type and the same (number of) argument(s), if any. For example, the above declared delegate is of type void and it does not take any argument. you can define a corresponding method as follows:

 

定义委托之后,委托只是为方法提供一个模板,但是并不提供具体的方法。如果要使用,你必须定义一个方法去执行它。这个方法必须和委托具有相同的返回值类型和相同的参数。针对上面的委托可以定义如下的方法:

 

public delegate void Simple();

public class Exercise
{
    public void Welcome()
    {
        Console.WriteLine("Welcome to the Wonderful World of C# Programming!");
    }
}

With such a method implemented, you can associate it to the name of the delegate. To do that, where you want to use the method, declare a variable of the type of the delegate and assign the method to the delegate variable. Because you are assigning the method to a delegate, one of the rules of delegates is that you must not apply the parentheses to the method. Here is an example

 

通过这样的一个方法的实现,你可以关联到一个委托的实例上。 在你要使用这个方法的地方,声明一个委托的变量,然后把这个方法赋值给这个委托变量。

 

public class Program
{
    static int Main()
    {
        Exercise exo = new Exercise();

        Simple msg = exo.Welcome;

        return 0;
    }
}

exo.Welcome 是这个方法,赋值给一个委托变量 Simple msg.

Once you have assigned a method to a delegate variable, you can use the delegate variable as if it were a defined method. That is, you can call as you would a normal method. Here is an example:

 

一旦你把一个方法赋值给了一个委托变量,你就可以像使用一个已经定义的方法一样使用一个委托变量。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public delegate void Simple();

public class Exercise
{
    public void Welcome()
    {
        Console.WriteLine("Welcome to the Wonderful World of C# Programming!");
    }
}

namespace Delegates
{
    public class Program
    {
        static int Main()
        {
            Exercise exo = new Exercise();

            Simple msg = exo.Welcome;

            msg();

            return 0;
        }
    }
}

 

A Static Method for a Delegate  静态方法的委托

In the above example, we had to declare a variable of the (Exercise) class before accessing the method. An alternative is to create the associated method as static. That way, you would not need to declare the variable first. Here is an example:

using System;

public delegate void Simple();

public class Exercise
{
    public static void Welcome()
    {
        Console.WriteLine("Welcome to the Wonderful World of C# Programming!");
    }
}

public class Program
{
    static int Main()
    {
        Simple msg = Exercise.Welcome;

        msg();

        return 0;
    }
}

 

 

Exercise.Welcome调用Excerise类的静态方法,并复制给委托实例msg.

【上篇】
【下篇】

抱歉!评论已关闭.