代码不起作用,请看看 [英] Code is not working,pls have a look

查看:125
本文介绍了代码不起作用,请看看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public partial class _Default : System.Web.UI.Page
    {
        public delegate void mydelegate();
        public event mydelegate myevent;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            myevent += new mydelegate(method1);
            myevent += new mydelegate(method2);
            myevent += new mydelegate(method3);
            myevent += new mydelegate(method4);
        }

        public void method1()
        {

            Response.Write("Method1");
            throw new Exception();

        }
        public void method2()
        {

            Response.Write("Method2");

        }
        public void method3()
        {

            Response.Write("Method3");

        }
        public void method4()
        {

            Response.Write("Method4");

        }



我的上述代码无效,即点击按钮方法1,2,3,4没有被调用。

先谢谢。


my above code is not working i.e. on button click method1,2,3,4 are not getting called.
Thanks in Advance.

推荐答案

好吧不 - 他们不会。你根本就没有调用它们 - 你只是将它们添加到代理行动时要调用的方法列表中。事实上,每次按下按钮,你都会在列表中再添加四个方法,所以如果你确实调用了代理本身,在第一次按下之后它会调用每一个,在第二次按下后它会调用每个两次,等等。



试试这个:

Well no - they won't. You aren't calling them at all - you are just adding them to the list of methods to call when you do action the delegate. In fact, each time you press the button, you add four more methods to the list, so if you did call the delegate itself, after the first press it would call each one once, after the second press it would call each one twice, and so on.

Try this:
protected void Page_Load(object sender, EventArgs e)
{
    myevent += new mydelegate(method1);
    myevent += new mydelegate(method2);
    myevent += new mydelegate(method3);
    myevent += new mydelegate(method4);
}
protected void Button1_Click(object sender, EventArgs e)
{

    if (myevent != null)
    {
        myevent();
    }
}


这篇关于代码不起作用,请看看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆