在我看来,代表似乎是需要学习的具有挑战性的概念之一。
根据我的理解,委托是一个方法指针,它在运行时指向特定的方法。
我给委托举的一个例子是在文件处理期间,可以在调用方法之前执行一些文件操作,并在方法调用后释放文件资源。在这里使用委托可以提高可重用性。
我的问题是,你能告诉我日常编程中委托的其他实际用法吗?
感谢就是进步!
发布于 2012-01-06 15:10:00
委托在与自定义事件处理程序一起使用时非常有用。
委托是您可以在运行时为调用方法定义的规则。
例如,公有委托void NameIndicator( string name );
可以将方法绑定到委托并将其注册到事件。
请参考下面的示例。
public delegate void NameIndicator( string name );
class Program
{
static void Main( string[] args )
{
//Create the instance of the class
Car car = new Car( "Audi" );
//Register the event with the corresponding method using the delegate
car.Name += new NameIndicator( Name );
//Call the start to invoke the Name method below at runtime.
car.Start();
Console.Read();
}
/// <summary>
/// The method that can subscribe the event of the defined class.
/// </summary>
/// <param name="name">Name assigned from the caller.</param>
private static void Name( string name )
{
Console.WriteLine( name );
}
}
public class Car
{
//Event for the car class.
public event NameIndicator Name;
string name;
public Car( string nameParam )
{
name = nameParam;
}
//Invoke the event when the start method is called.
public virtual void Start()
{
Name( name );
}
}发布于 2011-11-09 14:31:39
总的来说,委托最主要的用法是通过事件及其处理程序。我不知道你是否已经意识到这一点,因为你的问题的表达方式,但每次你写
someObj.SomeEvent += SomeMethod;您使用的是委托,具体地说,SomeMethod由委托实例包装。
发布于 2011-11-09 14:33:02
查看http://csharpindepth.com/Articles/Chapter2/Events.aspx
在这里输入太多了
https://stackoverflow.com/questions/8061186
复制相似问题