事件委托-----------------------

sss222ddd 2013-09-23 04:53:13

public delegate void MyDel();
public class myDel
{
public static event MyDel catshout;
public static void ratrun()
{
Console.WriteLine("run");
}
public static void test()
{
catshout += delegate {
Console.WriteLine(1);
};
}
}
//调用该方法 没有输出"run"
myDel.test();

为什么呢
...全文
94 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
_学而时习之_ 2013-09-23
  • 打赏
  • 举报
回复
委托类似于C/C++的函数指针,根本上可以认为是一个方法。 将事件挂上,就相当于是火车头挂上了车箱,但是如果火车头不走,车箱也肯定不可走的。而火车头走,就是执行方法或者触发事件。这也在另一点上可以说明,事件可以像车箱一相不断的挂上去,只要火车头一走,车箱就都会动起来,只是先挂的先执行,后挂的后执行。
sss222ddd 2013-09-23
  • 打赏
  • 举报
回复
引用 6 楼 xxdddail 的回复:
只是将事件挂上了,并没有执行 catshout。需要加上。
public static void test()
        {
            catshout += delegate {
                Console.WriteLine(1);
            };
            catshout();
        }
catshout 不是事件么 可以当方法用?
_学而时习之_ 2013-09-23
  • 打赏
  • 举报
回复
只是将事件挂上了,并没有执行 catshout。需要加上。
public static void test()
        {
            catshout += delegate {
                Console.WriteLine(1);
            };
            catshout();
        }
sss222ddd 2013-09-23
  • 打赏
  • 举报
回复

public delegate void MyDel();
    public class myDel
    {
        public static event MyDel catshout;
        public static void ratrun()
        {
            Console.WriteLine("run");
        }
        public static void test()
        {
            catshout += new MyDel(ratrun);
        }
    }
源码应该是这样的。。。。
sss222ddd 2013-09-23
  • 打赏
  • 举报
回复
引用 3 楼 gomoku 的回复:
catshout += delegate...只是订阅事件
那怎么触发呢?
gomoku 2013-09-23
  • 打赏
  • 举报
回复
catshout += delegate...只是订阅事件
gomoku 2013-09-23
  • 打赏
  • 举报
回复
catshout += delegate...至少订阅事件。事件本身还没有得到触发。
cheng2005 2013-09-23
  • 打赏
  • 举报
回复
我就没看出来为什么要输出"run",甚至都没发现ratrun()这个方法有被调用的地方。 楼主你知道自己在说什么吗?

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧