c#编码技巧(三):EventArgs的使用

本文介绍了一种在C#中利用EventArgs类实现不同类之间信息传递的方法。通过将Student类和Teacher类继承自EventArgs,可以简化消息传递过程并提高代码复用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 c#编码技巧(三):EventArgs的使用

如果有多个类要打印信息,如Student类,Teacher类,School类...如下代码。各类统一继承于EventArgs的话,那么传参就很方便了。

using System;
using System.Collections.Generic;


namespace ConsoleTest
{
    class Program
    {

        //把打印信息统一为一个函数,一个EventArgs参数。
        private static string ShowMessage(EventArgs e)
        {
            if (e is Student)               //判断参数类型
            {
                var student = e as Student; //把参数转换为Student类
                return student.Name + ", address = " + student.Address;

            }
            else if (e is Teacher)
            {
                var teacher = e as Teacher;
                return teacher.Name + ", course = " + teacher.Course;
            }
            else
                return "Not found";
        }
        static void Main(string[] args)
        {

            Console.WriteLine(ShowMessage(new Student("James","杭州")));
            Console.WriteLine(ShowMessage(new Teacher("Jack", "英语")));
            Console.ReadKey();
        }


        //继承于EventArgs,便于传参
        public class Student : EventArgs    
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public string Address { get; set; }
            public Student(string name, string address)
            {
                this.Name = name;
                this.Address = address;
            }
        }

        //继承于EventArgs,便于传参
        public class Teacher : EventArgs
        {
            public string Name { get; set; }
            public string ClassId { get; set; }
            public string Course { get; set; }
            public Teacher(string name, string course)
            {
                this.Name = name;
                this.Course = course;
            }
        }
    }
}

输出:

James, address = 杭州
Jack, course = 英语

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值