[C#] C#事件与接口实例讲解分析

来源:互联网 发布:linux var目录 清理 编辑:程序博客网 时间:2024/06/07 03:32
C#事件与接口实例讲解分析
初学c#的,对于事件与接口感到迷惑不解,不明白它们之间的关系,通过资料以下实例能说明它们之间的关系:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
    //有事件就需要有委托
    public delegate void mydele();

    public interface ItextInt//定义接口
    {
        event mydele event1;//事件
        void myFunction();//方法
    }

    public class TestClass : ItextInt//实现接口
    {
        public event mydele event1;//实现接口中的事件
        public void myFunction()//实现接口中的方法
        {
            event1();//执行这个事件(注意,要执行哪个事件,我不管,以后在程序里可以由情况来决定,即到时再给这个事件委托要执行的方法)
        }
    }

    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 键盘按下时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            TestClass myTestClass = new TestClass();
            switch (e.KeyCode.ToString())
            {
                case "Right":
                    myTestClass.event1 += new mydele(myTestClass_eventR);//给事件委托要执行的方法
                    myTestClass.myFunction();
                    break;

                case "Left":
                    myTestClass.event1 += new mydele(myTestClass_eventL);//给事件委托要执行的方法
                    myTestClass.myFunction();
                    break;

                case "Up":
                    myTestClass.event1 += new mydele(myTestClass_eventT);//给事件委托要执行的方法
                    myTestClass.myFunction();
                    break;

                case "Down":
                    myTestClass.event1 += new mydele(myTestClass_eventB);//给事件委托要执行的方法
                    myTestClass.myFunction();
                    break;
            }
        }

        /// <summary>
        /// 以下四个为要测试的函数
        /// </summary>
        private void myTestClass_eventR()
        {
            this.textBox1.Text = "这是右边!";
        }

        private void myTestClass_eventL()
        {
            this.textBox1.Text = "这是左边!";
        }


        private void myTestClass_eventT()
        {
            this.textBox1.Text = "这是上边!";
        }

        private void myTestClass_eventB()
        {
            this.textBox1.Text = "这是下边!";
        }

    }
原创粉丝点击