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 = 英语