C#学习笔记五---委托(来自微软MSDN)
1 委托
委托 是一种引用方法的类型。一旦为委托分配了方法,委托将与该方法具有完全相同的行为。委托方法的使用可以像其他任何方法一样,具有参数和返回值 ,如下面的示例所示:
C#
public delegate int PerformCalculation(int x, int y);
与委托的签名(由返回类型和参数组成)匹配的任何方法都可以分配给该委托。这样就可以通过编程方式来更改方法调用,还可以向现有类中插入新代码。只要知道委托的签名,便可以分配自己的委托方法。
将方法作为参数进行引用的能力使委托成为定义回调方法的理想选择。 例如,可以向排序算法传递对比较两个对象的方法的引用。分离比较代码使得可以采用更通用的方式编写算法。
委托概述
委托具有以下特点:
· 委托类似于 C++ 函数指针,但它是类型安全的。
· 委托允许将方法作为参数进行传递。
· 委托可用于定义回调方法。
· 委托可以链接在一起;
2 使用委托
委托 是一种安全地封装方法的类型 ,它与 C 和 C++ 中的函数指针类似。与 C 中的函数指针不同,委托是面向对象的、类型安全的和保险的。委托的类型由委托的名称定义 。
下面的示例声明了一个名为 Del 的委托,该委托可以封装一个采用字符串 作为参数并返回 void 的方法。
C#
public delegate void Del(string message);
构造委托对象时,通常提供委托将包装的方法的名称或使用匿名方法 。实例化委托后,委托将把对它进行的方法调用传递给方法。调用方传递给委托的参数被传递给方法,来自方法的返回值(如果有)由委托返回给调用方。这被称为调用委托。可以将一个实例化的委托视为被包装的方法本身来调用该委托 。
例如:
C#
// Create a method for a delegate.
public static void DelegateMethod(string message)
{
System.Console.WriteLine(message);
}
C#
// Instantiate the delegate.
Del handler = DelegateMethod;
// Call the delegate.
handler("Hello World" );
委托类型派生自 .NET Framework 中的 Delegate 类。委托类型是 密封 的,不能从 Delegate 中派生委托类型,也不可能从中派生自定义类。由于实例化委托是一个对象,所以可以将其作为参数进行传递,也可以将其赋值给属性。这样,方法便可以将一个委托作为参数来接受,并且以后可以调用该委托。这称为异步回调,是在较长的进程完成后用来通知调用方的常用方法。以这种方式使用委托时,使用委托的代码无需了解有关所用方法的实现方面的任何信息。。
回调的另一个常见用法是定义自定义的比较方法并将该委托传递给排序方法。它允许调用方的代码成为排序算法的一部分。
下面的示例方法使用 Del 类型作为参数:
C#
public void MethodWithCallback(int param1, int param2, Del callback)
{
callback("The number is: " + (param1 + param2).ToString());
}
然后可以将上面创建的委托传递给该方法:
C#
MethodWithCallback(1, 2, handler);
在控制台中将收到下面的输出:
The number is: 3
在将委托用作抽象概念时, MethodWithCallback 不需要直接调用控制台 -- 设计它时无需考虑控制台。 MethodWithCallback 的作用只是准备字符串并将该字符串传递给其他方法。此功能特别强大,因为委托的方法可以使用任意数量的参数。
将委托构造为包装实例方法时,该委托将同时引用实例和方法。除了它所包装的方法外,委托不了解实例类型,所以只要任意类型的对象中具有与委托签名相匹配的方法,委托就可以引用该对象。将委托构造为包装静态方法时,它只引用方法。考虑下列声明:
C#
public class MethodClass
{
public void Method1(string message) { }
public void Method2(string message) { }
}
加上前面显示的静态 DelegateMethod ,现在我们有三个方法可由 Del 实例进行包装。
调用委托时,它可以调用多个方法。这称为多路广播。若要向委托的方法列表(调用列表)中添加额外的方法,只需使用加法运算符或加法赋值运算符( “+” 或 “+=” )添加两个委托。例如:
C#
MethodClass obj = new MethodClass();
Del d1 = obj.Method1;
Del d2 = obj.Method2;
Del d3 = DelegateMethod;
//Both types of assignment are valid.
Del allMethodsDelegate = d1 + d2;
allMethodsDelegate += d3;
此时, allMethodsDelegate 在其调用列表中包含三个方法 -- Method1 、 Method2 和 DelegateMethod 。原来的三个委托 d1 、 d2 和 d3 保持不变。调用 allMethodsDelegate 时,将按顺序调用所有这三个方法。如果委托使用引用参数,则引用将依次传递给三个方法中的每个方法,由一个方法引起的更改对下一个方法是可见的。如果任一方法引发了异常,而在该方法内未捕获该异常,则该异常将传递给委托的调用方,并且不再对调用列表中后面的方法进行调用。如果委托具有返回值和 / 或输出参数,它将返回最后调用的方法的返回值和参数。若要从调用列表中移除方法,请使用减法运算符或减法赋值运算符( “-” 或 “-=” )。例如:
C#
//remove Method1
allMethodsDelegate -= d1;
// copy AllMethodsDelegate while removing d2
Del oneMethodDelegate = allMethodsDelegate - d2;
由于委托类型派生自 System.Delegate ,所以可在委托上调用该类定义的方法和属性。例如,为了找出委托的调用列表中的方法数,您可以编写下面的代码:
C#
int invocationCount = d1.GetInvocationList().GetLength(0);
在调用列表中具有多个方法的委托派生自 MulticastDelegate ,这是 System.Delegate 的子类。由于两个类都支持 GetInvocationList ,所以上面的代码在两种情况下都适用。
多路广播委托广泛用于事件处理中。事件源对象向已注册接收该事件的接收方对象发送事件通知。为了为事件注册,接收方创建了旨在处理事件的方法,然后为该方法创建委托并将该委托传递给事件源。事件发生时,源将调用委托。然后,委托调用接收方的事件处理方法并传送事件数据。。
在编译时,对分配了两种不同类型的委托进行比较将产生编译错误。如果委托实例静态地属于类型 System.Delegate ,则允许进行比较,但在运行时将返回 false 。例如:
C#
delegate void Delegate1();
delegate void Delegate2();
static void method(Delegate1 d, Delegate2 e, System.Delegate f)
{
// Compile-time error.
//Console.WriteLine(d == e);
// OK at compile-time. False if the run-time type of f
//is not the same as that of d.
System.Console.WriteLine(d == f);
}
3. 命名方法
委托 可以与命名方法关联。使用命名的方法对委托进行实例化时,该方法将作为参数传递 ,
例如:
C#
// Declare a delegate:
delegate void Del(int x);
// Define a named method:
void DoWork(int k) { /* ... */ }
// Instantiate the delegate using the method as a parameter:
Del d = obj.DoWork;
这被称为使用命名的方法。使用命名方法构造的委托可以封装静态 方法或实例方法。在以前的 C# 版本中,使用命名的方法是对委托进行实例化的唯一方式。但是,在创建新方法的系统开销不必要时, C# 2.0 允许您对委托进行实例化,并立即指定委托将在被调用时处理的代码块。这些被称为匿名方法( C# 编程指南) 。
备注
作为委托参数传递的方法必须与委托声明具有相同的签名。
委托实例可以封装静态或实例方法。
尽管委托可以使用 out 参数,但不推荐将其用于多路广播事件委托中,因为无法确定要调用哪个委托。
示例 1
以下是声明及使用委托的一个简单示例。注意,委托 Del 和关联的方法 MultiplyNumbers 具有相同的签名
C#
// Declare a delegate
delegate void Del(int i, double j);
class MathClass
{
static void Main()
{
MathClass m = new MathClass();
// Delegate instantiation using "MultiplyNumbers"
Del d = m.MultiplyNumbers;
// Invoke the delegate object.
System.Console.WriteLine("Invoking the delegate using 'MultiplyNumbers':" );
for (int i = 1; i <= 5; i++)
{
d(i, 2);
}
}
// Declare the associated method.
void MultiplyNumbers(int m, double n)
{
System.Console.Write(m * n + " " );
}
}
输出
Invoking the delegate using 'MultiplyNumbers':
2 4 6 8 10
示例 2
在下面的示例中,一个委托被同时映射到静态方法和实例方法,并分别返回特定的信息。
C#
// Declare a delegate
delegate void Del();
class SampleClass
{
public void InstanceMethod()
{
System.Console.WriteLine("A message from the instance method." );
}
static public void StaticMethod()
{
System.Console.WriteLine("A message from the static method." );
}
}
class TestSampleClass
{
static void Main()
{
SampleClass sc = new SampleClass();
// Map the delegate to the instance method:
Del d = sc.InstanceMethod;
d();
// Map to the static method:
d = SampleClass.StaticMethod;
d();
}
}
输出
A message from the instance method.
A message from the static method.
4. 匿名方法
在 2.0 之前的 C# 版本中,声明委托 的唯一方法是使用命名方法 。 C# 2.0 引入了匿名方法。要将代码块传递为委托参数,创建匿名方法则是唯一的方法 。
例如:
C#
// Create a handler for a click event
button1.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Click!" ); };
或
C#
// Create a delegate instance
delegate void Del(int x);
// Instantiate the delegate using an anonymous method
Del d = delegate(int k) { /* ... */ };
如果使用匿名方法,则不必创建单独的方法,因此减少了实例化委托所需的编码系统开销。
例如,如果创建方法所需的系统开销是不必要的,在委托的位置指定代码块就非常有用。启动新线程即是一个很好的示例。无需为委托创建更多方法,线程类即可创建一个线程并且包含该线程执行的代码。
C#
void StartThread()
{
System.Threading.Thread t1 = new System.Threading.Thread
(delegate()
{
System.Console.Write("Hello, " );
System.Console.WriteLine("World!" );
});
t1.Start();
}
备注
匿名方法的参数的范围是 anonymous-method-block 。
在目标在块外部的匿名方法块内使用跳转语句(如 goto 、 break 或 continue )是错误的。在目标在块内部的匿名方法块外部使用跳转语句(如 goto 、 break 或 continue )也是错误的。
如果局部变量和参数的范围包含匿名方法声明,则该局部变量和参数称为该匿名方法的外部变量或捕获变量 。例如,下面代码段中的 n 即是一个外部变量:
C#
int n = 0;
Del d = delegate() { System.Console.WriteLine("Copy #:{0}" , ++n); };
与局部变量不同,外部变量的生命周期一直持续到引用该匿名方法的委托符合垃圾回收的条件为止。对 n 的引用是在创建该委托时捕获的。
在 anonymous-method-block 中不能访问任何不安全代码。
示例
· 使委托与匿名方法关联。
· 使委托与命名方法 ( DoWork ) 关联。
两种方法都会在调用委托时显示一条消息。
C#
// Declare a delegate
delegate void Printer(string s);
class TestClass
{
static void Main()
{
// Instatiate the delegate type using an anonymous method:
Printer p = delegate(string j)
{
System.Console.WriteLine(j);
};
// Results from the anonymous delegate call:
p("The delegate using the anonymous method is called." );
// The delegate instantiation using a named method "DoWork":
p = new Printer(TestClass.DoWork);
// Results from the old style delegate call:
p("The delegate using the named method is called." );
}
// The method associated with the named delegate:
static void DoWork(string k)
{
System.Console.WriteLine(k);
}
}
输出
The delegate using the anonymous method is called.
The delegate using the named method is called.
5 何时使用委托而不使用接口
委托和接口都允许类设计器分离类型声明和实现。给定的接口 可由任何 类 或结构 继承和实现;可以为任何类中的方法创建委托 ,前提是该方法符合委托的方法签名。接口引用或委托可由不了解实现该接口或委托方法的类的对象使用。既然存在这些相似性,那么类设计器何时应使用委托,何时又该使用接口呢?
在以下情况中使用委托:
· 当使用事件设计模式时。
· 当封装静态方法可取时。
· 当调用方不需要访问实现该方法的对象中的其他属性、方法或接口时。
· 需要方便的组合。
· 当类可能需要该方法的多个实现时。
在以下情况中使用接口:
· 当存在一组可能被调用的相关方法时。
· 当类只需要方法的单个实现时。
· 当使用接口的类想要将该接口强制转换为其他接口或类类型时。
· 当正在实现的方法链接到类的类型或标识时:例如比较方法。
使用单一方法接口而不使用委托的一个很好的示例是 IComparable 或 IComparable 。 IComparable 声明 CompareTo 方法,该方法返回一个整数,以指定相同类型的两个对象之间的小于、等于或大于关系。 IComparable 可用作排序算法的基础,虽然将委托比较方法用作排序算法的基础是有效的,但是并不理想。因为进行比较的能力属于类,而比较算法不会在运行时改变,所以单一方法接口是理想的。
6 委托中的协变和逆变
将方法签名与 委托 类型匹配时,协变和逆变为您提供了一定程度的灵活性。协变允许方法具有的派生返回类型比委托中定义的更多。逆变允许方法具有的派生参数类型比委托类型中的更少。
示例 1 (协变)
本示例演示如何将委托与具有返回类型的方法一起使用,这些返回类型派生自委托签名中的返回类型。由 SecondHandler 返回的数据类型是 Dogs 类型,它是由委托中定义的 Mammals 类型派生的。
C#
class Mammals
{
}
class Dogs : Mammals
{
}
class Program
{
// Define the delegate.
public delegate Mammals HandlerMethod();
public static Mammals FirstHandler()
{
return null ;
}
public static Dogs SecondHandler()
{
return null ;
}
static void Main()
{
HandlerMethod handler1 = FirstHandler;
// Covariance allows this delegate.
HandlerMethod handler2 = SecondHandler;
}
}
示例 2 (逆变)
本示例演示如何将委托与具有某个类型的参数的方法一起使用,这些参数是委托签名参数类型的基类型。通过逆变,以前必须使用若干个不同处理程序的地方现在只要使用一个事件处理程序即可 。如,现在可以创建一个接收 EventArgs 输入参数的事件处理程序,然后,可以将该处理程序与发送 MouseEventArgs 类型(作为参数)的 Button.MouseClick 事件一起使用,也可以将该处理程序与发送 KeyEventArgs 参数的 TextBox.KeyDown 事件一起使用。
C#
System.DateTime lastActivity;
public Form1()
{
InitializeComponent();
lastActivity = new System.DateTime();
this .textBox1.KeyDown += this .MultiHandler; //works with KeyEventArgs
this .button1.MouseClick += this .MultiHandler; //works with MouseEventArgs
}
// Event hander for any event with an EventArgs or
// derived class in the second parameter
private void MultiHandler(object sender, System.EventArgs e)
{
lastActivity = System.DateTime.Now;
}
请参见
7. 如何:合并委托(多路广播委托)
本示例演示如何组合多路广播委托。 委托 对象的一个用途在于,可以使用 + 运算符将它们分配给一个要成为多路广播委托的委托实例。组合的委托可调用组成它的那两个委托。只有相同类型的委托才可以组合。
- 运算符可用来从组合的委托移除组件委托。
示例
C#
delegate void
Del(string
s);
class
TestClass
{
static
void
Hello(string
s)
{
System.Console.WriteLine("
Hello, {0}!"
, s);
}
static
void
Goodbye(string
s)
{
System.Console.WriteLine("
Goodbye, {0}!"
, s);
}
static
void
Main()
{
Del a, b, c, d;
// Create the delegate object a that references
// the method Hello:
a = Hello;
// Create the delegate object b that references
// the method Goodbye:
b = Goodbye;
// The two delegates, a and b, are composed to form c:
c = a + b;
// Remove a from the composed delegate, leaving d,
// which calls only the method Goodbye:
d = c - a;
System.Console.WriteLine("Invoking delegate a:"
);
a("A"
);
System.Console.WriteLine("Invoking delegate b:"
);
b("B"
);
System.Console.WriteLine("Invoking delegate c:"
);
c("C"
);
System.Console.WriteLine("Invoking delegate d:"
);
d("D"
);
}
}
输出
Invoking delegate a:
Hello, A!
Invoking delegate b:
Goodbye, B!
Invoking delegate c:
Hello, C!
Goodbye, C!
Invoking delegate d:
Goodbye, D!
请参见
7.如何:声明、实例化和使用委托
委托的声明如下所示:
C#
public
delegate void
Del<T>(T item);
public
void
Notify(int
i) { }
C#
Del
<int
> d1 = new
Del<int
>(Notify);
在 C# 2.0 中,还可以使用下面的简化语法来声明委托:
C#
Del
<int
> d2 = Notify;
下面的示例阐释声明、实例化和使用委托。 BookDB 类封装一个书店数据库,它维护一个书籍数据库。它公开 ProcessPaperbackBooks 方法,该方法在数据库中查找所有平装书,并对每本平装书调用一个委托。所使用的 delegate 类型称为 ProcessBookDelegate 。 Test 类使用该类输出平装书的书名和平均价格。
委托的使用促进了书店数据库和客户代码之间功能的良好分隔。客户代码不知道书籍的存储方式和书店代码查找平装书的方式。书店代码也不知道找到平装书后将对平装书进行什么处理。
示例
C#
// A set of classes for handling a bookstore:
namespace
Bookstore
{
using
System.Collections;
// Describes a book in the book list:
public
struct Book
{
public
string
Title;
// Title of the book.
public
string
Author;
// Author of the book.
public
decimal Price;
// Price of the book.
public
bool
Paperback;
// Is it paperback?
public
Book(string
title, string
author, decimal price, bool
paperBack)
{
Title = title;
Author = author;
Price = price;
Paperback = paperBack;
}
}
// Declare a delegate type for processing a book:
public
delegate void
ProcessBookDelegate(Book book);
// Maintains a book database.
public
class
BookDB
{
// List of all books in the database:
ArrayList list = new
ArrayList();
// Add a book to the database:
public
void
AddBook(string
title, string
author, decimal price, bool
paperBack)
{
list.Add(new
Book(title, author, price, paperBack));
}
// Call a passed-in delegate on each paperback book to process it:
public
void
ProcessPaperbackBooks(ProcessBookDelegate processBook)
{
foreach
(Book b in
list)
{
if
(b.Paperback)
// Calling the delegate:
processBook(b);
}
}
}
}
// Using the Bookstore classes:
namespace
BookTestClient
{
using
Bookstore;
// Class to total and average prices of books:
class
PriceTotaller
{
int
countBooks = 0;
decimal priceBooks = 0.0m;
internal void
AddBookToTotal(Book book)
{
countBooks += 1;
priceBooks += book.Price;
}
internal decimal AveragePrice()
{
return
priceBooks / countBooks;
}
}
// Class to test the book database:
class
TestBookDB
{
// Print the title of the book.
static
void
PrintTitle(Book b)
{
System.Console.WriteLine("
{0}"
, b.Title);
}
// Execution starts here.
static
void
Main()
{
BookDB bookDB = new
BookDB();
// Initialize the database with some books:
AddBooks(bookDB);
// Print all the titles of paperbacks:
System.Console.WriteLine("Paperback Book Titles:"
);
// Create a new delegate object associated with the static
// method Test.PrintTitle:
bookDB.ProcessPaperbackBooks(PrintTitle);
// Get the average price of a paperback by using
// a PriceTotaller object:
PriceTotaller totaller = new
PriceTotaller();
// Create a new delegate object associated with the nonstatic
// method AddBookToTotal on the object totaller:
bookDB.ProcessPaperbackBooks(totaller.AddBookToTotal);
System.Console.WriteLine("Average Paperback Book Price: ${0:#.##}"
,
totaller.AveragePrice());
}
// Initialize the book database with some test books:
static
void
AddBooks(BookDB bookDB)
{
bookDB.AddBook("The C Programming Language"
, "Brian W. Kernighan and Dennis M. Ritchie"
, 19.95m, true
);
bookDB.AddBook("The Unicode Standard 2.0"
, "The Unicode Consortium"
, 39.95m, true
);
bookDB.AddBook("The MS-DOS Encyclopedia"
, "Ray Duncan"
, 129.95m, false
);
bookDB.AddBook("Dogbert's Clues for the Clueless"
, "Scott Adams"
, 12.00m, true
);
}
}
}
输出
Paperback Book Titles:
The C Programming Language
The Unicode Standard 2.0
Dogbert's Clues for the Clueless
Average Paperback Book Price: $23.97
可靠编程
- 声明委托。
下列语句:
C#
public
delegate void
ProcessBookDelegate(Book book);
声明一个新的委托类型。每个委托类型都描述参数的数目和类型,以及它可以封装的方法的返回值类型。每当需要一组新的参数类型或新的返回值类型时,都必须声明一个新的委托类型。
- 实例化委托。
声明了委托类型后,必须创建委托对象并使之与特定方法关联。在上面的示例中,这是通过将 PrintTitle 方法传递给 ProcessPaperbackBooks 方法来完成的,如下所示:
C#
bookDB.ProcessPaperbackBooks(PrintTitle);
这将创建与 静态 方法 Test.PrintTitle 关联的新委托对象。类似地,对象 totaller 的非静态方法 AddBookToTotal 是按如下方式传递的:
C#
bookDB.ProcessPaperbackBooks(totaller.AddBookToTotal);
在两个示例中,都向 ProcessPaperbackBooks 方法传递了一个新的委托对象。
委托一旦创建,它的关联方法就不能更改;委托对象是不可变的。
- 调用委托。
创建委托对象后,通常将委托对象传递给将调用该委托的其他代码。通过委托对象的名称(后面跟着要传递给委托的参数,括在括号内)调用委托对象。下面是委托调用的示例:
C#
processBook(b);
与本例一样,可以通过使用 BeginInvoke 和 EndInvoke 方法同步或异步调用委托。