首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >委托的实际实现

委托的实际实现
EN

Stack Overflow用户
提问于 2011-11-09 14:28:16
回答 4查看 934关注 0票数 0

在我看来,代表似乎是需要学习的具有挑战性的概念之一。

根据我的理解,委托是一个方法指针,它在运行时指向特定的方法。

我给委托举的一个例子是在文件处理期间,可以在调用方法之前执行一些文件操作,并在方法调用后释放文件资源。在这里使用委托可以提高可重用性。

我的问题是,你能告诉我日常编程中委托的其他实际用法吗?

感谢就是进步!

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-01-06 15:10:00

委托在与自定义事件处理程序一起使用时非常有用。

委托是您可以在运行时为调用方法定义的规则。

例如,公有委托void NameIndicator( string name );

可以将方法绑定到委托并将其注册到事件。

请参考下面的示例。

代码语言:javascript
复制
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 );
    }
}
票数 0
EN

Stack Overflow用户

发布于 2011-11-09 14:31:39

总的来说,委托最主要的用法是通过事件及其处理程序。我不知道你是否已经意识到这一点,因为你的问题的表达方式,但每次你写

代码语言:javascript
复制
someObj.SomeEvent += SomeMethod;

您使用的是委托,具体地说,SomeMethod由委托实例包装。

票数 3
EN

Stack Overflow用户

发布于 2011-11-09 14:33:02

查看http://csharpindepth.com/Articles/Chapter2/Events.aspx

在这里输入太多了

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8061186

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档