1,delegate是什么?
msdn定义:委托是一种引用方法的类型.一旦为委托分配了方法,委托将与该方法具有完全相同的行为.委托方法的使用可以像其他任何方法一样,具有参数和返回值.
其声明如下:
public delegate void TestDelegate( string message);
多路广播委托:可以使用 + 运算符将它们分配给一个要成为多路广播委托的委托实例。组合的委托可调用组成它的那两个委托。只有相同类型的委托才可以组合。
- 运算符可用来从组合的委托移除组件委托。
2,delegate的特点?
delegate类似于c++的函数指针,但它是类型安全的;
delegate是引用类型,使用前必须new下(static除外);
委托允许将方法作为参数进行传递;
委托可以链接在一起;例如,可以对一个事件调用多个方法;
方法不需要与委托签名精确匹配.参见协变和逆变(协变允许将带有派生返回类型的方法用作委托,逆变允许将带有派生参数的方法用作委托。);
C#2.0引入了匿名方法的概念,此类方法允许将代码作为参数传递,以代替单独定义的方法.
3,delegate怎么用?
三步:声明declare
public delegate void Del<T>(T item);
public void Notify(int i) { }
实例化instantiation
Del<int> d1 = new Del<int>(Notify);
在 C# 2.0 中,还可以使用下面的简化语法来声明委托:
调用invocation
4,为什么用delegate?
还不是很清楚,按我的理解就是写出面向对象高质量的代码,设计模块中观察者模块就以delegate/event实现
5,何时使用委托而不使用接口?(msdn)
委托和接口都允许类设计器分离类型声明和实现。给定的接口可由任何类或结构继承和实现;可以为任何类中的方法创建委托,前提是该方法符合委托的方法签名。接口引用或委托可由不了解实现该接口或委托方法的类的对象使用。既然存在这些相似性,那么类设计器何时应使用委托,何时又该使用接口呢?
在以下情况中使用委托:
- 当使用事件设计模式时。
- 当封装静态方法可取时。
- 当调用方不需要访问实现该方法的对象中的其他属性、方法或接口时。
- 需要方便的组合。
- 当类可能需要该方法的多个实现时。
在以下情况中使用接口:
- 当存在一组可能被调用的相关方法时。
- 当类只需要方法的单个实现时。
- 当使用接口的类想要将该接口强制转换为其他接口或类类型时。
- 当正在实现的方法链接到类的类型或标识时:例如比较方法。
6,举例说明:
// copy by msdn,changed by me
using System;
// Declare delegate -- defines required signature:
delegate void SampleDelegate( string message);
class MainClass
... {
// Regular method that matches signature:
static void SampleDelegateMethod(string message)
...{
Console.WriteLine(message);
}
//non-static method that mathches signature;
public void Sample(string message)
...{
Console.WriteLine(message);
}
static void Main()
...{
// Instantiate delegate with named method:
SampleDelegate d1 = SampleDelegateMethod;
// Instantiate delegate with anonymous method:
SampleDelegate d2 = delegate(string message)
...{
Console.WriteLine(message);
};
// Create an instance of the delegate with static method;
SampleDelegate d3=new SampleDelegate(SampleDelegateMethod);
//Create an instance of the delegate with new instance;
MainClass myclass = new MainClass();
SampleDelegate d4 = new SampleDelegate(myclass.Sample);
// Invoke delegate d1:
d1("Hello");
// Invoke delegate d2:
d2(" World");
d3("static");
d4("non-static");
}
}