木子屋 Dnawo's BLOG

实例化委托的两种方法:命名方法和匿名方法

👤 dnawo 📅 2007-12-29 👁 4442 👍 0 💬 0 🔄 来源:本站原创
1.命名方法

namespace ConsoleApplication1
{
    class Class1
    {
        delegate void print(string msg);

        static void showmsg(string msg)
        {
            Console.WriteLine("hello," + msg);
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            print p = showmsg;
            p("aaa");
        }
    }
}

2.匿名方法

namespace ConsoleApplication1
{
    class Class1
    {
        delegate void print(string msg);

        static void Main(string[] args)
        {
            print p = delegate(string msg)
            {
                Console.WriteLine("hello," + msg);
                Console.ReadKey();
            };
            p("aaa");
        }
    }
}

使用匿名方法,则不必创建单独的方法,因此减少了实例化委托所需的编码系统开销。如果创建方法所需的系统开销是不必要的,在委托的位置指定代码块就非常有用。

评论(0)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 何时使用委托而不使用接口 下一篇 → 程序员的成长从开窍开始