关于委托和事件的问题

来源:百度知道 编辑:UC知道 时间:2024/05/17 15:51:06
using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{

public delegate void MyDelegate();//这里是定义一个委托吧?怎么没看到用呢?
class Program
{

static void Main(string[] args)
{
Teacher teacher = new Teacher();
Student tom = new Student("tom");
Student mike = new Student("mike");
teacher.Book(tom);
teacher.Book(mike);
teacher.Question();
}
}

class Teacher
{
private event MyDelegate All;//这句是什么意思又是event又是MyDelegate……
public void Book(Student stu) {
All += stu.Answer;//同上All是什么类型的?
}
public void Question() {
Console.WriteLine("start");
All();
}
}

class Student
{

定义了一个委托 他是一个类 可以装一个对象和一个方法

然后定义了一个事件 他是一个类成员 其实就是一个字段 这个事件的类型是刚才定义的委托类型 名字叫All

All+= 意思是给事件注册一个方法 当引发事件的时候会调用这个方法

生命一个委托,多看书

汗。。。你的public delegate void MyDelegate()怎么写到类的外面去了。。

MyDelegate写在类外和类内部都可以,就看MyDelegate的使用范围了,