using System;
class Program
{
static void Main(string[] args) {
Teacher t = new Teacher();
t.AskStudentDoSomething();
}
}
public delegate void Something(string name);
public class Teacher
{
public void AskStudentDoSomething() {
Student student = new Student("Peter");
Something s = new Something(A);
student.DoSomething(s);
}
private void A(string name) {
Console.WriteLine(name + " should go to buy some books.");
}
}
public class Student
{
private string name;
public Student(string name) {
this.name = name;
}
public void DoSomething(Something something) {
// Console.WriteLine("should go to buy some books.");// 写死是不对的,应该在 Teacher 按需写内容,使用 delegate
something(name);
}
}
using System;
/*
event 和 delegate 的关系就好像字段和属性的关系;
event 会限制 delegate 不能够直接赋值操作,防止将委托替换掉,只能使用 += 和 -= 来绑定
或解除绑定;
event 还限定了delegate 只能在定义的类中被调用;
*/
class Program
{
static void Main(string[] args) {
Teacher t = new Teacher();
t.askStudentDoSomething();
}
}
public delegate void Something(string name);
public class Teacher
{
public void askStudentDoSomething() {
Student s = new Student("Peter");
// 使用了 event 之后就不能直接给委托赋值 必须使用 += -= 来绑定或解除绑定
s.something += new Something(A);
// 使用了 event 之后就不能直接在 Student 外调用委托
// s.something("Peter");
s.Do();
}
private void A(string name) {
Console.WriteLine(name + " should go to read more books.");
}
}
public class Student
{
private string name;
public event Something something;
public Student(string name) {
this.name = name;
}
public void Do() {
something(name);
}
}
///
///
//class Program
//{
// static void Main(string[] args) {
// Teacher t = new Teacher();
// t.askStudentDoSomething();
// }
//}
//public delegate void Something(string name);
//public class Teacher
//{
// public void askStudentDoSomething() {
// Student s = new Student("Peter");
// s.something = new Something(A);
// s.Do();
// }
// private void A(string name) {
// Console.WriteLine(name + " should go to read more books.");
// }
//}
//public class Student
//{
// private string name;
// public Something something;
// public Student(string name) {
// this.name = name;
// }
// public void Do() {
// something(name);
// }
//}
///