C#委托

C# 委托类似于C语言C++中函数的指针。委托是一个引用类型变量,它保存对方法的引用。 引用可以在运行时更改。

委托一般用于实现事件和回调方法。所有委托都隐式地从System.Delegate类派生。

声明委托

委托声明确定委托可引用的方法。委托可以引用一个方法,它具有与委托相同的签名。

例如,考虑下面一个委托:

public delegate int MyDelegate (string s);

上述委托可用于引用具有单个字符串参数并返回int类型变量的任何方法。

委托声明的语法是:

delegate <return type> <delegate-name> <parameter list>

实例化委托

当声明了一个委托类型后,必须要使用new关键字创建一个委托对象,并将其与特定的方法相关联。创建代理时,传递给新表达式的参数类似于方法调用,但不包含方法的参数。 例如:

public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);

以下示例演示了可以用于引用取整数参数并返回整数值的方法委托的声明,实例化和使用。

using System;

delegate int NumberChanger(int n);
namespace DelegateAppl
{
   class TestDelegate
   {
      static int num = 10;
      public static int AddNum(int p)
      {
         num += p;
         return num;
      }

      public static int MultNum(int q)
      {
         num *= q;
         return num;
      }
      public static int getNum()
      {
         return num;
      }

      static void Main(string[] args)
      {
         //create delegate instances
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);

         //calling the methods using the delegate objects
         nc1(25);
         Console.WriteLine("Value of Num: {0}", getNum());
         nc2(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}

当上述代码被编译并执行时,它产生以下结果:

Value of Num: 35
Value of Num: 175

委托组播

代理对象可以使用“+”运算符来组合。一个委托调用它由两个委托组成。只能组合相同类型的委托。“-”运算符可用于从组合委托中删除组件委托。

使用委托的这个属性,可以创建一个方法的调用列表,该方法将在调用委托时调用。这称为委托组播。以下程序演示了一个委托组播:

using System;

delegate int NumberChanger(int n);
namespace DelegateAppl
{
    class TestDelegate
    {
        static int num = 100;
        public static int AddNum(int p)
        {
            num += p;
            return num;
        }

        public static int MultNum(int q)
        {
            num *= q;
            return num;
        }

        public static int getNum()
        {
            return num;
        }

        static void Main(string[] args)
        {
            //create delegate instances
            NumberChanger nc;
            NumberChanger nc1 = new NumberChanger(AddNum);
            NumberChanger nc2 = new NumberChanger(MultNum);
            nc = nc1;
            nc += nc2;

            //calling multicast
            nc(5);
            Console.WriteLine("Value of Num: {0}", getNum());
            Console.ReadKey();
        }
    }
}

当上述代码被编译并执行时,它产生以下结果:

Value of Num: 525

使用委托

以下示例演示了使用委托。委托printString可用于引用方法,该方法将字符串作为输入,并且不返回任何内容。

使用这个委托来调用两个方法,第一个将字符串打印到控制台,第二个打印到一个文件中:

using System;
using System.IO;

namespace DelegateAppl
{
   class PrintString
   {
      static FileStream fs;
      static StreamWriter sw;

      // delegate declaration
      public delegate void printString(string s);

      // this method prints to the console
      public static void WriteToScreen(string str)
      {
         Console.WriteLine("The String is: {0}", str);
      }

      //this method prints to a file
      public static void WriteToFile(string s)
      {
         fs = new FileStream("c:\\message.txt",
         FileMode.Append, FileAccess.Write);
         sw = new StreamWriter(fs);
         sw.WriteLine(s);
         sw.Flush();
         sw.Close();
         fs.Close();
      }

      // this method takes the delegate as parameter and uses it to
      // call the methods as required
      public static void sendString(printString ps)
      {
         ps("Hello World");
      }
      static void Main(string[] args)
      {
         printString ps1 = new printString(WriteToScreen);
         printString ps2 = new printString(WriteToFile);
         sendString(ps1);
         sendString(ps2);
         Console.ReadKey();
      }
   }
}

当上述代码被编译并执行时,它产生以下结果:

The String is: Hello World

上一篇: C#索引器 下一篇: C#事件