A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 马林康 中级黑马   /  2012-7-24 11:14  /  1427 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

委托中delegate 和Delegate类有什么关系?Delegate类怎么用?

评分

参与人数 1技术分 +1 收起 理由
宋天琪 + 1

查看全部评分

3 个回复

倒序浏览
1,委托(Delegate)类是一种数据结构,通过它可引用静态方法或引用类实例及该类的实例方法;
2,Delegate在搭载多个方法时,可以通过+=增加搭载的函数,也可以通过-=来去掉Delegate中的某个函数
3,class Program
    {
        static void OtherClassMethod()
       {
            Console.WriteLine("Delegate an other class's method");
        }

        static void Main(string[] args)
        {
            var test = new TestDelegate();

           //delegateMethod搭载了3个函数
            test.delegateMethod = new TestDelegate.DelegateMethod(test.NonStaticMethod);
            test.delegateMethod += new TestDelegate.DelegateMethod(TestDelegate.StaticMethod);
            test.delegateMethod += Program.OtherClassMethod;

            test.RunDelegateMethods();

        }
    }

    class TestDelegate
    {
        public delegate void DelegateMethod();  //声明了一个Delegate Type,DelegateMethod是类型

        public DelegateMethod delegateMethod;   //声明了一个Delegate对象,delegateMethod是对象

        public static void StaticMethod()  //调用静态方法
        {
            Console.WriteLine("Delegate a static method");
        }

        public void NonStaticMethod()  //调用非静态方法
        {
            Console.WriteLine("Delegate a non-static method");
        }

        public void RunDelegateMethods()
        {
            if(delegateMethod != null)
            {
                Console.WriteLine("---------");
                delegateMethod.Invoke();    //运行被搭载的函数
                Console.WriteLine("---------");
            }
        }
    }

评分

参与人数 1技术分 +1 收起 理由
宋天琪 + 1

查看全部评分

回复 使用道具 举报
delegate可以认为是一种函数的指针,一个delegate类型的实例代表可以代表一个方法,在实际使用中我们可以在不知道方法名称的情况下调用到这个方法。
委托(Delegate)类是一种数据结构,通过它可引用静态方法或引用类实例及该类的实例方法,Ddelegate类是委托类型的基类。

delegate的简单应用:
1.       定义delegate类型
2.       定义一个方法包含要执行的代码
3.       创建一个delegate实例
4.       调用delegate实例

评分

参与人数 1技术分 +1 收起 理由
宋天琪 + 1

查看全部评分

回复 使用道具 举报
这是我早期写的,不知道对你有没帮助,拿给你看看,委托只有在事件里才能深刻弄明白
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace 定义委托
{
    class Program
    {
        //委托是不能定义返回值的;
        delegate void delegateone();//定义了一个不包含参数的委托类型;
        delegate void delegatetwo(params int[] values);//定义了一个包含参数的委托类型;
        static void Methoddelegateone()
        {
            Console.WriteLine("Hello.World" + " " + "!");
        }
        static void Methoddelegatetwo(params int[] values)
        {
            for (int i = 0; i < values.Length - 1; i++)
            {
                for (int j = 0; j < values.Length - i - 1; j++)
                {
                    int temp;
                    if (values[j] <= values[j + 1])
                    {
                        temp = values[j];
                        values[j] = values[j + 1];
                        values[j + 1] = temp;

                    }
                }
            }
            foreach (int i in values)
            {
                Console.Write(i + " ");
            }
            Console.Write("\n");
        }
        static void MethoddelegatetwoAvg(params int[] values)
        {
            int sum = 0;
            for (int i = 0; i < values.Length;i++ )
            {
                sum += values[i];
            }
            Console.WriteLine("总成绩为{0}{1},平均成绩为{0}{2}"," ",sum,(double)sum/values.Length);
        }
        static void Main(string[] args)
        {
            ShowUi();
            
            int number=0;
            Console.WriteLine("请输入你们班级人数?");
            try
            {
                number = Convert.ToInt32(Console.ReadLine());
                if (number<0)
                {
                    MessageBox.Show("人数不能为负数");
                    return;
                }
                else
                {
                    Console.WriteLine("------------------------------------------------");
                }
            }
            catch
            {

                MessageBox.Show("人数只能是数字");
                return;
            }
            int [] score =new int[number];//这里的number必须先定义,赋值再使用;
            for (int i = 0; i < score.Length;i++ )
            {
                Console.WriteLine("请输入第{0}个学生的成绩?",i+1);
                try
                {
                    score[i] = Convert.ToInt32(Console.ReadLine());
                    if (score[i]<0||score[i]>100)
                    {
                        MessageBox.Show("学生成绩不能为负数,也不能大于100");
                        return;
                    }
                    else
                    {

                    }
                }
                catch
                {
                    MessageBox.Show("学生成绩只能是数字!");
                    return;
                }
            }

            delegateone onedelegate = new delegateone(Methoddelegateone);
            delegatetwo twodelegate=null;
            twodelegate+= new delegatetwo(Methoddelegatetwo);
            twodelegate += new delegatetwo(MethoddelegatetwoAvg);

            onedelegate();
            Console.Clear();
            Console.Write("你们班学生成绩最高分——>最低分为:");
            twodelegate(score);
            Console.ReadKey();

         
        }
       static  void ShowUi()
        {
            Console.WriteLine("********************************************");
            Console.WriteLine("**          计算班级学生成绩             **");
            Console.WriteLine("********************************************");
        }
    }
}



using System;

namespace 规范事件委托编码
{
    class Program
    {
        static void Main(string[] args)
        {
            Publish onepublish = new Publish();
            Subscriber zs = new Subscriber("张三");
            Subscriber ls = new Subscriber("李四");
            onepublish.PublishComputer += new Publish.PublishComputerEventHandler(zs.Receive);
            onepublish.PublishComputer += new Publish.PublishComputerEventHandler(ls.Receive);
            onepublish.PublishLife += new Publish.PublishLifeEventHandler(zs.Receive);
            onepublish.PublishLife += new Publish.PublishLifeEventHandler(ls.Receive);
            onepublish.isOnPublishComputer("电脑",Convert.ToDateTime ("2011-01-01"));
            onepublish.isonpublishlife("生活",Convert.ToDateTime("2011-01-01"));
            Console.WriteLine();
            Console.WriteLine("_______________________________________");
            Console.WriteLine("一年以后");
            Console.WriteLine("_______________________________________");
            onepublish.PublishComputer -= new Publish.PublishComputerEventHandler(zs.Receive);
            onepublish.isOnPublishComputer("电脑", Convert.ToDateTime("2012-01-01"));
            onepublish.isonpublishlife("生活", Convert.ToDateTime("2012-01-01"));
            Console.WriteLine();
            Console.WriteLine("_______________________________________");
            Console.WriteLine("过了三年");
            Console.WriteLine("_______________________________________");
            onepublish.PublishComputer -= new Publish.PublishComputerEventHandler(ls.Receive);
            onepublish.PublishLife -= new Publish.PublishLifeEventHandler(zs.Receive);
            onepublish.isOnPublishComputer("电脑", Convert.ToDateTime("2015-01-01"));
            onepublish.isonpublishlife("生活", Convert.ToDateTime("2015-01-01"));
            Console.ReadKey();







        }
    }
    class Publish
    {
       public  delegate void PublishComputerEventHandler(object sender,PubEventAges e);
       public  delegate void PublishLifeEventHandler(object sender,PubEventAges e);
       public event PublishComputerEventHandler PublishComputer;
       public event PublishLifeEventHandler PublishLife;
       protected virtual void onPublishComputer(PubEventAges e)
       {
           PublishComputerEventHandler handler = PublishComputer;
           if (handler !=null)
           {
               handler(this ,e);

           }

       }
       protected virtual void onPublishLife(PubEventAges e)
       {
           PublishLifeEventHandler handler = PublishLife;
           if(handler!=null)
           {
               handler(this ,e);
           }

       }
       public void isOnPublishComputer(string magzaine, DateTime Pubdate)
       {
           Console.WriteLine("发行"+magzaine);
           onPublishComputer(new PubEventAges (magzaine ,Pubdate));
       }
       public void isonpublishlife(string magazine,DateTime pubdate)
       {
           Console.WriteLine("发行"+magazine);
           onPublishLife(new PubEventAges (magazine,pubdate ));

       }

    }
    class PubEventAges : EventArgs
    {
        private readonly string m_magazineName;
        private readonly DateTime m_PubDate;
        public PubEventAges(string magazineName, DateTime PubDate)
        {
            m_magazineName = magazineName;
            m_PubDate = PubDate;
        }
        public string magazine
        {
            get { return m_magazineName; }
        }
        public DateTime pubdate
        {
            get { return m_PubDate; }
        }
    }
    class Subscriber
    {
        private string name;
        public Subscriber(string name)
        {
            this.name = name;
        }
        public void Receive(object sender,PubEventAges e)
        {
            Console.WriteLine(e.pubdate+ name +"收到"+e.magazine);
        }
    }

}

评分

参与人数 1技术分 +2 收起 理由
郑文 + 2

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马