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 "输入的字符不是数字";
            }
        }
    }

  • 相关阅读:
    7月30日 举办专注于微服务的.NET Conf Focus
    我和ABP vNext 的故事
    Windows环境搞好的Dockerfile文件 在Linux上报错了
    [LeetCode] 955. Delete Columns to Make Sorted II 删除列使其有序之二
    [LeetCode] 954. Array of Doubled Pairs 两倍数对儿数组
    上周热点回顾(8.3-8.9)团队
    发布新版首页“外婆新家”升级版:全新的UI,熟悉的味道团队
    上周热点回顾(7.27-8.2)团队
    终于换新颜:新版网站首页发布上线团队
    上周热点回顾(7.20-7.26)团队
  • 原文地址:https://www.cnblogs.com/duanlinlin/p/3142971.html
Copyright © 2011-2022 走看看