【发布时间】:2011-12-25 01:27:36
【问题描述】:
在我看来,代表似乎是一个具有挑战性的学习概念。
在我的理解中,delegate 是一个方法指针,它在运行时指向一个特定的方法。
我为委托做的一个例子是在文件处理期间,可以在调用方法之前执行一些文件操作,并在方法调用之后释放文件资源。在此处使用委托可以提高可重用性。
我的问题是,您能告诉我代理在日常编程中的其他实际用途吗?
先谢谢了!
【问题讨论】:
标签: c#
在我看来,代表似乎是一个具有挑战性的学习概念。
在我的理解中,delegate 是一个方法指针,它在运行时指向一个特定的方法。
我为委托做的一个例子是在文件处理期间,可以在调用方法之前执行一些文件操作,并在方法调用之后释放文件资源。在此处使用委托可以提高可重用性。
我的问题是,您能告诉我代理在日常编程中的其他实际用途吗?
先谢谢了!
【问题讨论】:
标签: c#
嗯,总的来说,委托最主要的用途是通过事件及其处理程序。由于您提出问题的方式,我无法判断您是否意识到这一点,但每次您写的时候
someObj.SomeEvent += SomeMethod;
您正在使用委托,具体来说,SomeMethod 正在被委托实例包装。
【讨论】:
【讨论】:
委托在与自定义事件处理程序一起使用时很有用。
委托是您可以在以下位置为您的调用方法定义的规则 运行时间。
例如 public delegate 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 );
}
}
【讨论】:
您还将使用委托与线程:
//Anynymous delegate
new Thread(delegate()
{
Console.WriteLine("Hello world form Thread");
});
//Lambda expression
new Thread(() =>
{
Console.WriteLine("Hello world form Thread");
});
看看 lambda 表达式,它很强大:Lambda expression
【讨论】: