zoukankan      html  css  js  c++  java
  • 怎么在项目中应用委托

    委托可以把一个方法作为参数代入另一个方法。委托可以理解为指向一个函数的指针。

    简单案例:文本框中只能输入数字,否则提示错误

    在项目中添加Web窗体和Web用户控件。

    Web用户控件前台样式:

    后台代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;


    namespace 委托的简单应用
    {
        public partial class WebUserControl1 : System.Web.UI.UserControl
        {
            public Number num;
            protected void Page_Load(object sender, EventArgs e)
            {


            }
            protected void Button1_Click(object sender, EventArgs e)
            {
                int result;

                if (int.TryParse(TextBox1.Text,out result)==false)
                {
                    if (num!=null)
                    {
                        this.Label1.Text = num();
                    }
                }
            }
            //定义的委托
            public delegate string Number();

        }
    }

    然后在Web船体中引用Web用户控件,在设计页面拖进Web用户控件

    Web船体的后台代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;


    namespace 委托的简单应用
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {


                #region 写在if当中是不正确的,只会加载页面的时候执行一次
                /* if (!IsPostBack)
                {
                    WebUserControl11.num = Error3;
                }*/
                #endregion



                //利用委托实现效果
                WebUserControl11.num = Error3;

            }


            //下面三个定义的是方法(函数及提示的错误信息)

           // P.S:三个函数方法可以直接写在Web用户控件里边
            private static string Error1()
            {
                return "输入不正确";
            }
            private static string Error2()
            {
                return "请输入数字";
            }
            private static string Error3()
            {
                return "输入的字符不是数字";
            }
        }
    }

  • 相关阅读:
    Go学习2-切片
    Go学习1-MOD
    lua学习之逻辑运算符not,and,or
    google protobuf c++ 反射
    我要谴责一下,你们复制别人的答案好歹仔细看看
    远程登录redis
    openssl进行RSA加解密(C++)
    linux通过进程名查看其占用端口
    简体字丶冯|服务网关kong-docker安装
    简体字冯|docker-安装docker私有库
  • 原文地址:https://www.cnblogs.com/duanlinlin/p/3142971.html
Copyright © 2011-2022 走看看